Spring boot 启动完成后执行部分代码逻辑

前言

在日常开发过程中经常回遇到服务启动完成就要执行部分逻辑代码的情况,例如:删除临时文件,清楚缓存信息,读取配置文件,数据库连接,需要开机自启动等操作,实现的方法有很多,接下来为各位介绍一下个人经常使用到的几种方式。

实现方式
第一种 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 方法

总结

前两种方式基本能满足日常开发,如果大家有更好的方式或者建议环境大家评论。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值