Springboot启动后执行方法的方式

@PostConstruct

在BeanPostProcessor的postProcessBeforeInitialization中执行
在(应用启动完毕之前)执行的

# 在依赖注入后执行
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done.
Indicating initialization methods to call after configuration of a bean.
# 一个类中只能有一个(实际Spring中有多个也会执行)
Only one method can be annotated with this annotation.
# 被标注的方法不能有参数
Lifecycle method annotation requires a no-arg method
The method MUST NOT have any parameters.
返回值是void,不要是static
[https://docs.oracle.com/javase/8/docs/api/javax/annotation/PostConstruct.html]
@PreDestroy
Indicating destruction methods to call when the context is shutting down.

一个类中有多个@PostConstruct时,执行的顺序是随机的
是因为getDeclaredMethods获取类中的方法时,返回的Method数组中的method元素顺序(是随机的)

1.org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
#doCreateBean
#applyMergedBeanDefinitionPostProcessors(调用2)
#initializeBean
(1.调用aware接口
(2.各种beanPostProcessor的postProcessBeforeInitialization方法(@PostConstruct在这里执行)
(3.调用InitializingBean接口
(4.调用init-method方法(如果指定了的话)
(5.各种beanPostProcessor的postProcessAfterInitialization方法
#applyBeanPostProcessorsBeforeInitialization(执行各种beanPostProcessor的postProcessBeforeInitialization方法)

2.(InitDestroyAnnotationBeanPostProcessor的子类)
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
#postProcessMergedBeanDefinition(调用3)
#findResourceMetadata

3.org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor
#postProcessMergedBeanDefinition
#findLifecycleMetadata(找出被@PostConstruct和@PreDestroy标注的方法)
#buildLifecycleMetadata
.LifecycleMetadata#checkConfigMembers
InitDestroyAnnotationBeanPostProcessor类的
postProcessBeforeInitialization方法中会调用@PostConstruct标注的方法
postProcessBeforeDestruction方法中会调用@PreDestroy标注的方法

ApplicationRunner和CommandLineRunner

这两者区别不大
都是在应用启动完毕后才执行

Interface used to indicate that a bean should run when it is contained within a SpringApplication.
Multiple ApplicationRunner/CommandLineRunner beans can be defined within the same application context
and can be ordered using the Ordered interface or @Order annotation.
是在这里被调用的
org.springframework.boot.SpringApplication
#run(java.lang.String...)
#callRunners
先执行ApplicationRunner,紧接着再执行CommandLineRunner

ApplicationRunner

猜你喜欢

转载自blog.csdn.net/qq_53318060/article/details/131064652