問題來源:在Listener監聽器中無法使用Spring容器的@Resource或者@Autowired 註解的方法注入bean,因為,在web Server容器中,無論是Servlet,Filter,還是Listener都不是Spring容器管理的,因此我們都無法在這些類中直接使用Spring註解的方式來注入我們需要的對象。
在這裡,Servlet的整個生命週期都是由Servlet容器來處理的。如果把它硬放到Spring容器中去建立,Servlet對象是可被Spring容器建出來,但Servlet容器可能跟本就不知此Servlet存在,因不在它的容器中。所以,servlet交給web server來管理,不要交給spring管理。
我們在Java web 應用中會使用到監聽器來完成一些操作,比如說使用Session監聽器來監聽Session的變化,通常情況下我們會用javaee規範中的Listener去實現,例如
public class TestListener implements HttpSessionAttributeListener,ServletContextListener{ @Override public void attributeAdded(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } @Override public void attributeRemoved(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } @Override public void attributeReplaced(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub }}
現在,我們想在這個監聽器裡面注入bean,如果使用Spring註解的方式注入bean如下面這樣:
@Resourceprivate AdvertisementServiceImpl advertisementServiceImpl;
然而以上代碼會在項目啟動時拋出null 指標異常。AdvertisementServiceImpl的執行個體並沒有成功注入。這是為什麼呢。要理解這個問題,首先要區分Listener的生命週期和spring管理的bean的生命週期。
(1)Listener的生命週期是由servlet容器(例如tomcat)管理的,項目啟動時上例中的TestListener是由servlet容器執行個體化並調用其contextInitialized方法,而servlet容器並不認得@Resource註解,因此導致AdvertisementServiceImpl執行個體注入失敗。
(2)而spring容器中的bean的生命週期是由spring容器管理的。 那麼該如何在spring容器外面擷取到spring容器bean執行個體的引用呢。這就需要用到spring為我們提供的WebApplicationContextUtils工具類,該工具類的作用是擷取到spring容器的引用,進而擷取到我們需要的bean執行個體。代碼如下
@Overridepublic void contextInitialized(ServletContextEvent sce) { WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); this.advertisementServiceImpl=(AdvertisementServiceImpl)applicationContext.getBean("advertisementServiceImpl"); } 然後在spring配置:
<bean id="xxxService">xxx.xxx.xxx.xxxService</bean>