Spring Boot如何实现自动运行代码呢?
下文笔者讲述SpringBoot项目启动时,加载资源的方法分享
由于SpringBoot在启动时,需运行一些代码,用于加载相应的资源,那么如何实现这种需求呢?下文笔者将一一道来,如下所示
由于SpringBoot在启动时,需运行一些代码,用于加载相应的资源,那么如何实现这种需求呢?下文笔者将一一道来,如下所示
实现思路:
方式1:
使用static静态代码块实现
方式2:
使用@PostConstruct注解实现
例:
@Component
public class TestPostConstruct {
static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
TestApplicationRunner
@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("order1:TestApplicationRunner");
}
}
Testcommandlinerunner
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:TestCommandLineRunner");
}
}
SpringBoot启动流程
Spring应用启动过程,
先自动扫描有@Component注解类,
加载类并初始化对象进行自动注入
加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法
在对象注入完成后,
调用带有@PostConstruct注解方法
当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法
所以SpringBoot的加载顺序为static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


