首页 > java > >springBoot启动时自动执行代码的几种方式

springBoot启动时自动执行代码的几种方式

时间:2022-04-27浏览次数:

@Component
public class initConfig {
    //1、静态代码块
    static {
        System.out.println("aaaaa");
        System.out.println("===================");
    }

    //2、构造方法
    public initConfig(){
        System.out.println("bbbbbb");
        System.out.println("===================");
    }
    //3、注解
    @PostConstruct
    public void init(){
        System.out.println("ccccccc");
        System.out.println("===================");
    }
}
@Component
@Order(1)  //执行顺序
public class TestApplicationRunner implements ApplicationRunner{
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("order1:TestApplicationRunner");
    }
}
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("order2:TestCommandLineRunner");
    }
}


总结:
加载顺序为static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner