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

@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"); } }

springBoot启动时自动执行代码的几种方式
文章图片

【springBoot启动时自动执行代码的几种方式】总结:
加载顺序为static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner

    推荐阅读