在springboot项目中启动时需要预加载一些资源,这时需要通过自启动的方式来执行指定任务的代码,可以通过static代码块、构造方法、注解@PostConstruct、ApplicationRunner、CommandLineRunner的方式来实现。下面对几种方式进行简单的分析。
- static代码块:static静态代码块在类加载的时候即自动执行。
- 构造方法:在对象初始化时自动执行,执行顺序在static静态代码块之后。
- 注解@PostConstruct:@PostConstruct注解使用在方法上,在对象依赖注入初始化之后执行。
- ApplicationRunner:在spring容器启动完成之后执行,可以通过注解@Order来指定执行顺序。
- CommandLineRunner:在spring容器启动完成之后执行,可以通过注解@Order来指定执行顺序。
实例
@Component
public class TestComponent {
static {
System.out.println("static");
}
public TestComponent() {
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");
}
}
测试结果
在springboot工程启动过程中,会自动扫描@Component注解的类,加载类并初始化对象进行注入,加载类时首先执行了static代码块中的代码,然后初始化对象时执行了构造方法,注入后执行了@PostConstruct注解的方法,当spring容器启动完成之后根据@Order注解分别顺序执行了run方法。