Spring bean 初始化顺序
1.初始化顺序
@Bean(initMethod = "init", destroyMethod = "cleanup")
public Person person() {
return new Person();
}
package com.example.demo;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @author :ouruyi
* @version 1.0
* @date :Created in 2021/5/21 17:50
* 功能描述:
*/
public class Person implements InitializingBean, DisposableBean {
@Value("${server.port}")
private int port;
@PostConstruct
public void postConstruct() {
System.out.println("@PostConstruct");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("org.springframework.beans.factory.InitializingBean#afterPropertiesSet");
}
@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("org.springframework.beans.factory.DisposableBean#destroy");
}
public void init() {
System.out.println("org.springframework.context.annotation.Bean#initMethod");
}
public void cleanup() {
System.out.println("org.springframework.context.annotation.Bean#destroyMethod");
}
}
输出:
@PostConstruct
org.springframework.beans.factory.InitializingBean#afterPropertiesSet
org.springframework.context.annotation.Bean#initMethod
@PreDestroy
org.springframework.beans.factory.DisposableBean#destroy
org.springframework.context.annotation.Bean#destroyMethod
2.源码解析
说明:
填充值:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
=>AutowiredAnnotationBeanPostProcessor
初始化:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
=>org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods