복붙노트

[SPRING] JBoss의 서블릿에서 Spring 빈에 접근하기

SPRING

JBoss의 서블릿에서 Spring 빈에 접근하기

Spring bean에서 메소드를 호출 할 JBoss에 간단한 서블릿을 작성하려고합니다. 목적은 사용자가 URL을 눌러 내부 작업을 시작하도록 허용하는 것입니다.

서블릿에서 Spring Bean에 대한 참조를 얻는 가장 쉬운 방법은 무엇입니까?

JBoss 웹 서비스를 사용하면 @Resource 주석을 사용하여 WebServiceContext를 서비스 클래스에 삽입 할 수 있습니다. 일반 서블릿에서 작동하는 것과 비슷한 것이 있습니까? 이 특정 문제를 해결하기위한 웹 서비스는 너트를 부수기 위해 슬레지 해머를 사용합니다.

해결법

  1. ==============================

    1.서블릿은 WebApplicationContextUtils를 사용하여 애플리케이션 컨텍스트를 가져올 수 있지만 서블릿 코드는 Spring 프레임 워크에 직접 종속된다.

    서블릿은 WebApplicationContextUtils를 사용하여 애플리케이션 컨텍스트를 가져올 수 있지만 서블릿 코드는 Spring 프레임 워크에 직접 종속된다.

    또 다른 해결책은 Spring 빈을 애트리뷰트로서 서블릿 컨텍스트로 내보내도록 애플리케이션 컨텍스트를 구성하는 것입니다.

    <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
      <property name="attributes">
        <map>
          <entry key="jobbie" value-ref="springifiedJobbie"/>
        </map>
      </property>
    </bean>
    

    서블릿은 서블릿 컨텍스트에서

    SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");
    
  2. ==============================

    2.이를 수행하는 훨씬 더 정교한 방법이 있습니다. 다음과 같은 것을 만들 수있는 org.springframework.web.context.support 안에 SpringBeanAutowiringSupport가 있습니다 :

    이를 수행하는 훨씬 더 정교한 방법이 있습니다. 다음과 같은 것을 만들 수있는 org.springframework.web.context.support 안에 SpringBeanAutowiringSupport가 있습니다 :

    public class MyServlet extends HttpServlet {
    
      @Autowired
      private MyService myService;
    
      public void init(ServletConfig config) {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
          config.getServletContext());
      }
    }
    

    이렇게하면 Spring은 (예를 들어 ContextLoaderListener를 통해 생성 된) ServletContext에 연결된 ApplicationContext를 검색하고 해당 ApplicationContext에서 사용 가능한 Spring 빈을 삽입하게된다.

  3. ==============================

    3.나는 그것을 할 수있는 한 가지 방법을 찾았습니다.

    나는 그것을 할 수있는 한 가지 방법을 찾았습니다.

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie");
    
  4. from https://stackoverflow.com/questions/467235/access-spring-beans-from-a-servlet-in-jboss by cc-by-sa and MIT license