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

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

方式一 :@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即可

例如:

/***

* 做一些初始化操作

* 在服务启动后马上执行,并仅执行一次.

*/

public class ConfigInitSchedule {

@Resource

private DictionaryParam dictionaryParam;

public void initDictionary() {

System.out.println("refresh dictionary ");

dictionaryParam.refresh2();

}

}

执行时机

web服务(tomcat 或jetty)启动之后

配置

spring-quartz.xml的配置:

class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值