有哪些方法 实现服务启动之后,马上执行相关操作?
方式一 :@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>
来源:oschina
链接:https://my.oschina.net/u/121435/blog/1858503