java 如何在listener(監聽器) 中使用Spring容器管理bean

來源:互聯網
上載者:User

問題來源:在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>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.