实现服务启动之后,马上执行任务的几种方法

自闭症网瘾萝莉.ら 提交于 2019-12-07 19:38:20

有哪些方法 实现服务启动之后,马上执行相关操作?

方式一 :@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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!