1. 程式人生 > >Spring實現後臺的任務排程TimerTask和Quartz

Spring實現後臺的任務排程TimerTask和Quartz

有時候需要啟動一個後臺守護執行緒,做一些別的事情。這時候怎麼獲取spring裡的Service、Dao、Action等物件?(注意自己new一個是不行的,因為脫離了spring的管理,其中IoC資源都沒有被注入)。

一個解決辦法是,重新弄一個Spring:


   XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(
     "applicationContext.xml"));

   // 從配置檔案中獲取物件
   IService hello = (IService) factory.getBean("service");
   hello.service("Helloween");

   factory.destroySingletons();

這是最笨的辦法,也是不科學的。這樣的話,web中會有兩個spring容器,兩套service、dao等。

---------------------我是分割線----------------------------------

比較科學的辦法,是用Spring的方法獲取到當前的容器(也是當前應用下唯一的spring容器),並從中獲取資源。程式碼為:


   WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
   IService service = (IService) context.getBean("service");

--------------------我是分割線-------------------------

ContextLoader.getCurrentWebApplicationContext()方法 可以從spring的載入listener中追蹤到:

<listener>
   <listener-class>
    org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>

我 用:WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
   IService service = (IService) context.getBean("service");

類方法來獲取注入的bean,解決了以上問題。