1. 程式人生 > >web服務啟動spring自己主動運行ApplicationListener的使用方法

web服務啟動spring自己主動運行ApplicationListener的使用方法

addclass tty -m pan pre contex oid his @override

我們知道。一般來說一個項目啟動時須要載入或者運行一些特殊的任務來初始化系統。通常的做法就是用servlet去初始化。可是servlet在使用spring bean時不能直接註入,還須要在web.xml配置。比較麻煩。今天介紹一下使用spring啟動初始化的方法。事實上非常easy,僅僅需兩步就能夠了。

  1. 實現ApplicationListener接口:
public class Init implements ApplicationListener<ContextRefreshedEvent>{

    @Override
    public void
onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent() == null){//root application context 沒有parent //TODO 這裏寫下將要初始化的內容 } } }
  1. 在spring applicationContex.xml中配置該bean
 <bean class="com.xx.xxx.Init"/>

這樣服務啟動時。就會自己主動載入並運行了。

‘).text(i)); }; $numbering.fadeIn(1700); }); });

web服務啟動spring自己主動運行ApplicationListener的使用方法