2011-04-01 4 views
12

나는 다음과 같은 클래스를 정의합니다. 나는 SomeServiceAnotherService을 구현하는 빈을 MyServletListener에 삽입하고 싶습니다. 이것이 가능합니까? 이 같은의존성 주사한다 서블릿 리스너

답변

23

뭔가 작업을해야합니다 :

public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener { 
    @Autowired 
    private SomeService someService;   
    @Autowired 
    private AnotherService anotherService; 

    public void contextInitialized(ServletContextEvent sce) { 
     WebApplicationContextUtils 
      .getRequiredWebApplicationContext(sce.getServletContext()) 
      .getAutowireCapableBeanFactory() 
      .autowireBean(this); 
    } 

    ... 
} 

리스너는 이후에 선언해야 봄의 ContextLoaderListenerweb.xml인치

+2

@Don :'(ServletContextEvent) contextInitalized'['ServletContextListener'] (HTTP에 정의된다 : //download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html#contextInitialized(javax.servlet.ServletContextEvent)) – ig0774

+0

잘 작동합니다. – Nico

+1

중요 : web.xml에서 MyServletListener 앞에 ContextLoaderListener를로드해야합니다. – Nico

10

조금 더 짧고 더 간단하면 SpringBeanAutowiringSupport 클래스를 사용하는 것입니다. 당신이해야 할 모든보다
은 이것이다 :

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 

그래서 axtavt에서 예제를 사용 :

public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener { 
    @Autowired 
    private SomeService someService;   
    @Autowired 
    private AnotherService anotherService; 

    public void contextInitialized(ServletContextEvent sce) { 
     SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 
    } 

    ... 
} 
+0

이것은 훨씬 간단한 방법이며 완벽하게 작동합니다. – Calabacin