SpringBoot 在项目启之后执行自定义方法的两种方式

前言

在测试配置中心的配置时,想在项目启动成功之后打印配置项,然后需要执行自定义的类
一般项目中也会在这个地方进行初始化数据的一些操作

方式一 实现 CommandLineRunner 接口

自定义类并实现 CommandLineRunner 接口,实现run()方法,需要执行的语句就放在 run() 方法中
例:

@Component
@Order(1)  // 控制类执行的顺序越小越靠前
public class StartInitializer implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("项目启动,执行 CommandLineRunner 实现类的方法");
    }
}

方式二 实现 ApplicationRunner 接口

自定义类并实现 ApplicationRunner 接口,实现run()方法,需要执行的语句就放在 run() 方法中
例:

@Component
@Order(2) // 控制类执行的顺序越小越靠前
public class AppInitializer implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("项目启动,执行 ApplicationRunner 实现类的方法");
    }
}

二者区别

区别在于实现方法 run() 中的参数类型不一样
实现 ApplicationRunner 接口的 run() 方法参数类型为: ApplicationArguments
实现 CommandLineRunner 接口的 run() 方法参数类型为: String...

实现效果


原文地址: https://www.cnblogs.com/inick/p/15250913.html

原文地址:https://www.cnblogs.com/inick/p/15250913.html