起源:blog.csdn.net/u011291072/article/details/81813662
前言
目前开发的SpringBoot我的项目在启动的时候须要预加载一些资源。而如何实现启动过程中执行代码,或启动胜利后执行,是有很多种形式能够抉择,咱们能够在static代码块中实现,也能够在构造方法里实现,也能够应用@PostConstruct
注解实现。
当然也能够去实现Spring的ApplicationRunner
与CommandLineRunner
接口去实现启动后运行的性能。在这里整顿一下,在这些地位执行的区别以及加载程序。
java本身的启动时加载形式
static代码块
static动态代码块,在类加载的时候即主动执行。
构造方法
在对象初始化时执行。执行程序在static动态代码块之后。
Spring启动时加载形式
@PostConstruct注解
PostConstruct注解应用在办法上,这个办法在对象依赖注入初始化之后执行。
ApplicationRunner和CommandLineRunner
SpringBoot提供了两个接口来实现Spring容器启动实现后执行的性能,两个接口别离为CommandLineRunner
和ApplicationRunner
。
这两个接口须要实现一个run办法,将代码在run中实现即可。这两个接口性能基本一致,其区别在于run办法的入参。ApplicationRunner
的run办法入参为ApplicationArguments
,为CommandLineRunner
的run办法入参为String数组。
何为ApplicationArguments
官网文档解释为:
Provides access to the arguments that were used to run a SpringApplication.
在Spring利用运行时应用的拜访利用参数。即咱们能够获取到SpringApplication.run(…)
的利用参数。
Order注解
当有多个类实现了CommandLineRunner
和ApplicationRunner
接口时,能够通过在类上增加@Order注解来设定运行程序。
代码测试
为了测试启动时运行的成果和程序,编写几个测试代码来运行看看。
Spring Boot 根底就不介绍了,举荐下这个实战教程:https://github.com/javastacks...
TestPostConstruct
@Componentpublic 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"); }}
执行后果
总结
Spring利用启动过程中,必定是要主动扫描有@Component
注解的类,加载类并初始化对象进行主动注入。加载类时首先要执行static动态代码块中的代码,之后再初始化对象时会执行构造方法。
在对象注入实现后,调用带有@PostConstruct
注解的办法。当容器启动胜利后,再依据@Order注解的顺序调用CommandLineRunner
和ApplicationRunner
接口类中的run办法。
因而,加载程序为static
>constructer
>@PostConstruct
>CommandLineRunner
和ApplicationRunner
.
近期热文举荐:
1.1,000+ 道 Java面试题及答案整顿(2022最新版)
2.劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4.别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!
5.《Java开发手册(嵩山版)》最新公布,速速下载!
感觉不错,别忘了顺手点赞+转发哦!