2011-04-01 50 views
12

在我的條紋程序,我定義了以下類:依賴注入的servlet監聽

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener { 

    private SomeService someService; 

    private AnotherService anotherService; 

    // remaining implementation omitted 
} 

這個應用程序的業務層使用Spring在一個XML文件中定義和電線在一起的一些服務組件。我想注入執行SomeServiceAnotherService的beans到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:'contextInitalized(ServletContextEvent)'是在['ServletContextListener'(HTTP定義: //download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html#contextInitialized(javax.servlet.ServletContextEvent)) – ig0774 2011-04-01 13:03:46

+0

這很棒! – Nico 2013-04-15 17:43:30

+1

重要提示:在web.xml中,ContextLoaderListener必須在MyServletListener之前加載。 – Nico 2013-04-15 17:53:24

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 2016-10-27 15:17:55