前言
在日常开发过程中经常回遇到服务启动完成就要执行部分逻辑代码的情况,例如:删除临时文件,清楚缓存信息,读取配置文件,数据库连接,需要开机自启动等操作,实现的方法有很多,接下来为各位介绍一下个人经常使用到的几种方式。
实现方式
第一种 CommandLineRunner
接口
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class CustomizeCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.debug("通过实现 CommandLineRunner 重写run方法实现。");
}
}
注意事项: 如果有多个实现,执行顺序使用@Order注解实现
第二种 ApplicationRunner
接口
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class CustomizeApplicationRunner implements ApplicationRunner {
@Override
public void run(String... args) throws Exception {
log.debug("通过实现 ApplicationRunner 重写run方法实现。");
}
}
注意事项:和上面的 CommandLineRunner 功能类似
第三种 ApplicationListener
接口
/**
* 注意: 如在springmvc 使用会执行两次,会在spring及springmvc创建容器时分别执行
* 只需校验一下有无父容器即可
*/
@Slf4j
@Component
public class CacheRefreshListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
log.debug("实现 ApplicationListener 并重写 onApplicationEvent 来实现。 ");
}
}
需要重写
onApplicationEvent
方法注意事项:
ContextRefreshedEvent
事件会在Spring容器初始化完成后以及刷新时触发。
第四种 @PostConstruct
注解
// 构造函数之后执行
@PostConstruct
public void initCache(){
log.debug("重置缓存");
}
有个坑,如果实现了懒加载,没有别的调用不会初始化,另外会出现找不到某个依赖的问题。
第五种 InitializingBean
接口
想要和spring容器一块初始化自己的组件时可以使用此方法
/**
* 自定义初始化自有组件
*
* @author our
*/
@Slf4j
@Component
public class CustomizeInitializingBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
log.debug("实现 InitializingBean 接口并重写 afterPropertiesSet 方法来实现");
}
}
注意事项:需重写
afterPropertiesSet
方法
总结
前两种方式基本能满足日常开发,如果大家有更好的方式或者建议环境大家评论。