实现服务启动以后,立刻执行任务的几种方法

有哪些方法 实现服务启动以后,立刻执行相关操做?java

方式一 :@PostConstruct

对类的要求

无,普通的java bean便可
例如:web

/***
     * 执行完构造方法以后就会执行该方法
     */
	@PostConstruct
    public void init() {
 System.out.println("初始化字典");
        refresh2();
    }

执行时机

类实例化以后spring

方式二: 实现org.springframework.context.ApplicationListener 的onApplicationEvent方法

对类的要求

必须使用SpringMVC的注解@Configuration ,
实现org.springframework.context.ApplicationListener 的onApplicationEvent方法tomcat

示例

例如:ide

/***
     * 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)启动以后this

配置

spring-quartz.xml的配置:code

<!-- 添加调度的任务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>
相关文章
相关标签/搜索