springBoot启动预加载方法

一、ApplicationRunner和CommandLineRunner

SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner和ApplicationRunner。

这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。

(1)、ApplicationRunner

1
2
3
4
5
6
7
8
9
10
11
@Component
public class ApplicationStartup
implements ApplicationRunner {
@Autowired
private EventlineService eventlineService;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("这是启动时默认测试项");
System.out.println("order1:ApplicationRunner");
}
}

(2)、CommandLineRunner

1
2
3
4
5
6
7
8
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:TestCommandLineRunner");
}
}

二、@PostConstruct注解

PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。

三、static代码块

static静态代码块,在类加载的时候即自动执行。

四、构造方法

在对象初始化时执行。执行顺序在static静态代码块之后。

二、三、四代码示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component
public class TestPostConstruct {

static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}

@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}

总结:

Spring应用启动过程中,肯定是要自动扫描有@Component注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法。在对象注入完成后,调用带有@PostConstruct注解的方法。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。因此,加载顺序为static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.


原文链接:https://blog.csdn.net/u011291072/article/details/8181366

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2018-2020 丁振莹
  • 访问人数: | 浏览次数:

你的每一分支持,是我努力下去的最大的力量 ٩(๑❛ᴗ❛๑)۶

支付宝
微信