乐趣区

关于java: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");
    }
}

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

退出移动版