實現服務啓動之後,馬上執行任務的幾種方法 原

有哪些方法 實現服務啓動之後,馬上執行相關操作?

方式一 :@PostConstruct

對類的要求

無,普通的java bean即可
例如:

 /***
     * 執行完構造方法之後就會執行該方法
     */
	@PostConstruct
    public void init() {
 System.out.println("初始化字典");
        refresh2();
    }

執行時機

類實例化之後

方式二: 實現org.springframework.context.ApplicationListener 的onApplicationEvent方法

對類的要求

必須使用SpringMVC的註解@Configuration ,
實現org.springframework.context.ApplicationListener 的onApplicationEvent方法

示例

例如:

 /***
     * Spring容器加載完成觸發,可用於初始化環境,準備測試數據、加載一些數據到內存
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        configType=getProperty("ConfigType");
        SpringMVCUtil.addCustomPropertySources(this.zookeeperSources, env);
 mkdirLogFolder(logFilePath);
    }

方式三:使用定時器

對類的要求

無,普通的java bean即可
例如:

/***
 * 做一些初始化操作<br />
 * 在服務啓動後馬上執行,並僅執行一次.
 */
public class ConfigInitSchedule {
    @Resource
    private DictionaryParam dictionaryParam;

    public void initDictionary() {
        System.out.println("refresh dictionary ");
        dictionaryParam.refresh2();
    }
}

執行時機

web服務(tomcat 或jetty)啓動之後

配置

spring-quartz.xml的配置:

<!-- 添加調度的任務bean 配置對應的class-->
    <bean id="myPrintSchedule" class="com.house.ujiayigou.config.ConfigInitSchedule"/>
    <!--配置調度具體執行的方法-->
    <bean id="myPrintDetail"
          class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="myPrintSchedule"/>
        <property name="targetMethod" value="initDictionary"/>
        <property name="concurrent" value="false"/>
    </bean>
    <!--配置調度執行的觸發的時間-->
    <bean id="myPrintTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="myPrintDetail"/>
        
        <property name="repeatCount" value="0"/>
    </bean>
    <!-- quartz的調度工廠 調度工廠只能有一個,多個調度任務在list中添加 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <!-- 所有的調度列表-->
                <ref local="myPrintTrigger"/>
            </list>
        </property>
    </bean>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章