如何在Springboot 项目启动后执行某些自定义代码逻辑

问题背景

最近在项目的过程中,需要在项目启动后去加载一些资源信息、执行某段特定逻辑等等初始化工作,譬如删除一些表的数据,清理缓存等等;

这时候我们就需要用到SpringBoot提供的开机自启的功能;

解决方案

SpringBoot给我们提供了两个方式:CommandLineRunner和ApplicationRunner,CommandLineRunner、ApplicationRunner接口是在容器启动成功后的最后一步回调,这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法;

第一种:CommandLineRunner

即建一个自己的事件监听类,实现CommandLineRunner接口:

@Component
public class MyStartRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("自己定义的第一个启动后事件开始执行。。。。。。。");
    }
}

如果需要多个监听类,只需要定义多个,然后通过@Order注解或者实现Order接口来标明加载顺序;

@Component
@Order(1)
public class MyStartRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("自己定义的第一个启动后事件开始执行。。。。。。。");
    }
}
@Component
@Order(2)
public class MyStartRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("自己定义的第二个启动后事件开始执行。。。。。。。");
    }
}

第二种:ApplicationRunner

创建自定义监听类,实现ApplicationRunner接口

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("我自定义的ApplicationRunner事件。。。。。。");
    }
}

ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口;

经验分享 程序员 微信小程序 职场和发展