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

java做服务启动_实现服务启动之后,马上执行任务的几种方法有哪些方法 实现服务启动之后 马上执行相关操作 方式一 PostConstruc 对类的要求 无 普通的 java bean 即可 例如 执行完构造方法之后就会执行该方法 PostConstruc public void init System out

大家好,我是讯享网,很高兴认识大家。

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

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

小讯
上一篇 2025-01-25 20:22
下一篇 2025-01-12 07:07

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/13070.html