2011-04-01 53 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