2011-04-01 38 views

cevap

23

şey çalışmalıdır:

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); 
    } 

    ... 
} 

telsizinde sonra beyan edilmelidir Bahar en ContextLoaderListenerweb.xml yılında.

+2

@Don: '(ServletContextEvent) contextInitalized' [ 'ServletContextListener'] (http tanımlanır: //download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html#contextInitialized(javax.servlet.ServletContextEvent) – ig0774

+0

Bu harika çalışıyor! – Nico

+1

Önemli: Web.xml'de ContextLoaderListener, MyServletListener'den önce yüklenmelidir. – Nico

10

Biraz daha kısa ve daha basit SpringBeanAutowiringSupport sınıfını kullanmaktır. Yapmanız gereken tek şey daha
şudur:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 

Yani axtavt gelen örneği kullanarak:

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

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

    ... 
} 
+0

Bu daha basit bir yol ve mükemmel çalışıyor. – Calabacin

İlgili konular