Spring Boot 启动时自动执行代码的几种方式,还有谁不会??
来源:blog.csdn.net/u011291072/article/details/81813662
前言
java自身的启动时加载方式
Spring启动时加载方式
代码测试
总结
前言
@PostConstruct注解实现。ApplicationRunner与CommandLineRunner接口去实现启动后运行的功能。在这里整理一下,在这些位置执行的区别以及加载顺序。java自身的启动时加载方式
static代码块
构造方法
Spring启动时加载方式
@PostConstruct注解
ApplicationRunner和CommandLineRunner
CommandLineRunner和ApplicationRunner。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。何为ApplicationArguments
Provides access to the arguments that were used to run a SpringApplication. 
SpringApplication.run(…)的应用参数。Order注解
CommandLineRunner和ApplicationRunner接口时,可以通过在类上添加@Order注解来设定运行顺序。代码测试
@Component 
public class TestPostConstruct {
static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
@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");
}
}
总结
@Component注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法。@PostConstruct注解的方法。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.如有文章对你有帮助,
“在看”和转发是对我最大的支持!
推荐:
评论


