懒得从spring源码角度分析,直接通过Demo演示总结bean的生命轨迹。

验证

依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>

结构

1
2
3
4
5
6
7
8
9
10
11
12
13
top.parak.springlearn
├───config
│ └───Config
├───common
│ └───KHighnessExecutingLog
├───life
│ └───KHighnessAwareBeanPostProcessor
│ └───KHighnessBeanFactoryPostProcessor
│ └───KHighnessBeanPostProcessor
└───service
│ └───UserInterface
│ └───UserService
└───KHighnessApplication

编码

日志输出记录类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package top.parak.springlearn.common;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicLong;

/**
* @author KHighness
* @since 2021-05-06
*/

public class KHighnessExecutingLog {
private final static AtomicLong COUNTER = new AtomicLong();
private final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

public static void info(String message) {
System.out.println(FORMATTER.format(LocalDateTime.now()) + " [" + COUNTER.incrementAndGet() + "] => " + message);
}
}

用户业务接口

1
2
3
4
5
6
7
8
9
10
11
package top.parak.springlearn.service;

/**
* @author KHighness
* @since 2021-04-01
*/

@FunctionalInterface
public interface UserInterface {
public void test();
}

用户业务接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package top.parak.springlearn.service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;
import top.parak.springlearn.common.KHighnessExecutingLog;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
* @author KHighness
* @since 2021-04-01
*/

@Component
public class UserService implements
/* 业务接口 */ UserInterface,
/* Bean接口 */ BeanNameAware, BeanClassLoaderAware, BeanFactoryAware,
/* 环境接口 */ EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, MessageSourceAware, ApplicationEventPublisherAware, ApplicationContextAware,
/* 后置接口 */ InitializingBean, DisposableBean {

private String name;

public UserService() {
KHighnessExecutingLog.info("构造函数: UserService.UserService() ");
}

public void setName(String name) {
this.name = name;
KHighnessExecutingLog.info("set函数: UserService.setName() ");
}

public void initMethod() {
KHighnessExecutingLog.info("自定义初始化: UserService.initMethod()");
}

public void destroyMethod() {
KHighnessExecutingLog.info("自定义销毁: UserService.destroyMethod()");
}

/**
* 传入bean名称
* @see BeanNameAware
*/
@Override
public void setBeanName(String s) {
KHighnessExecutingLog.info("传入bean名称: BeanNameAware.setBeanName()");
}

/**
* 传入bean类加载器
* @see BeanClassLoaderAware
*/
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
KHighnessExecutingLog.info("传入bean类加载器: BeanClassLoaderAware.setBeanClassLoader()");
}

/**
* 传入bean工厂
* @see BeanFactoryAware
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
KHighnessExecutingLog.info("传入bean工厂: BeanFactoryAware.setBeanFactory()");
}

/**
* 传入运行时环境
* @see EnvironmentAware
*/
@Override
public void setEnvironment(Environment environment) {
KHighnessExecutingLog.info("传入运行时环境: EnvironmentAware.setEnvironment()");
}

/**
* 传入文件解析器
* @see EmbeddedValueResolverAware
*/
@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
KHighnessExecutingLog.info("传入文件解析器: EmbeddedValueResolverAware.setEmbeddedValueResolver()");
}

/**
* 传入资源加载器
* @see ResourceLoaderAware
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
KHighnessExecutingLog.info("传入资源加载器: ResourceLoaderAware.setResourceLoader()");
}

/**
* 传入事件发布器
* @see ApplicationEventPublisherAware
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
KHighnessExecutingLog.info("传入事件发布器: ApplicationEventPublisherAware.setApplicationEventPublisher()");
}

/**
* 传入语言国际化
* @see MessageSourceAware
*/
@Override
public void setMessageSource(MessageSource messageSource) {
KHighnessExecutingLog.info("传入语言国际化: MessageSourceAware.setMessageSource()");
}

/**
* 传入应用上下文
* @see ApplicationContextAware
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
KHighnessExecutingLog.info("传入应用上下文: ApplicationContextAware.setApplicationContext()");
}

/**
* 初始化
* <p>如名,属性设置之后执行</p>
* @see InitializingBean
*/
@Override
public void afterPropertiesSet() throws Exception {
KHighnessExecutingLog.info("初始化: InitializingBean.afterPropertiesSet()");
}

/**
* 构造之后
*/
@PostConstruct
public void postConstruct() {
KHighnessExecutingLog.info("构造之后: @PostConstruct postConstruct()");
}

/**
* 销毁之前
*/
@PreDestroy
public void preDestroy() {
KHighnessExecutingLog.info("销毁之前: @PreDestroy preDestroy()");
}

/**
* 销毁bean
* @see DisposableBean
*/
@Override
public void destroy() throws Exception {
KHighnessExecutingLog.info("销毁bean: DisposableBean.destroy()");
}

/**
* 实现业务接口
* @see UserInterface
*/
@Override
public void test() {
KHighnessExecutingLog.info("业务逻辑: UserInterface.test() " + this.name);
}

}

后置处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package top.parak.springlearn.life;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import top.parak.springlearn.common.KHighnessExecutingLog;

/**
* @author KHighness
* @since 2021-05-06
*/

@Component
public class KHighnessBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
KHighnessExecutingLog.info("实例化前: BeanFactoryPostProcessor.postProcessBeanFactory()");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package top.parak.springlearn.life;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import top.parak.springlearn.common.KHighnessExecutingLog;

/**
* @author KHighness
* @since 2021-05-06
*/

@Component
public class KHighnessBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
KHighnessExecutingLog.info("初始化前: BeanPostProcessor.postProcessBeforeInitialization()");
return null;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
KHighnessExecutingLog.info("初始化后: BeanPostProcessor.postProcessAfterInitialization()");
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package top.parak.springlearn.life;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;
import top.parak.springlearn.common.KHighnessExecutingLog;
import top.parak.springlearn.service.UserService;

import javax.annotation.PostConstruct;
import java.lang.reflect.*;

/**
* @author KHighness
* @since 2021-04-01
*/

@Component
public class UserServiceBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (beanClass.equals(UserService.class)) {
KHighnessExecutingLog.info("实例化前: UserServiceBeanPostProcessor.postProcessBeforeInstantiation()");
}
return null;
}

/**
* 返回false则终止bean属性注入
*/
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (bean.getClass().equals(UserService.class)) {
KHighnessExecutingLog.info("实例化后: UserServiceBeanPostProcessor.postProcessAfterInstantiation() ");
}
return true;
}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("userService")) {
KHighnessExecutingLog.info("初始化前: UserServiceBeanPostProcessor.postProcessBeforeInitialization()");
for (Method method : bean.getClass().getMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
try {
method.invoke(bean);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return null;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("userService")) {
KHighnessExecutingLog.info("初始化后: UserServiceBeanPostProcessor.postProcessAfterInitialization() ");
// 模拟动态代理AOP
return Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
KHighnessExecutingLog.info("动态代理: Proxy.newProxyInstance()");
method.invoke(bean, args);
return null;
});
}
return null;
}
}

配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package top.parak.springlearn.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import top.parak.springlearn.service.UserService;

/**
* @author KHighness
* @since 2021-05-06
*/

@Configuration
@ComponentScan("top.parak.springlearn")
public class Config {

@Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public UserService userService() {
UserService userService = new UserService();
userService.setName("KHighness");
return userService;
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package top.parak.springlearn;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import top.parak.springlearn.config.Config;
import top.parak.springlearn.service.UserInterface;

/**
* @author KHighness
* @since 2021-03-30
*/

public class KHighnessApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
UserInterface userInterface = (UserInterface) applicationContext.getBean("userService");
userInterface.test();
applicationContext.close();
}
}

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2021-05-14 14:37:37.085 [1] => 实例化前: BeanFactoryPostProcessor.postProcessBeanFactory()
2021-05-14 14:37:37.118 [2] => 实例化前: InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()
2021-05-14 14:37:37.128 [3] => 构造函数: UserService.UserService()
2021-05-14 14:37:37.129 [4] => set函数: UserService.setName()
2021-05-14 14:37:37.131 [5] => 实例化后: InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()
2021-05-14 14:37:37.136 [6] => 传入bean名称: BeanNameAware.setBeanName()
2021-05-14 14:37:37.136 [7] => 传入bean类加载器: BeanClassLoaderAware.setBeanClassLoader()
2021-05-14 14:37:37.136 [8] => 传入bean工厂: BeanFactoryAware.setBeanFactory()
2021-05-14 14:37:37.137 [9] => 传入运行时环境: EnvironmentAware.setEnvironment()
2021-05-14 14:37:37.137 [10] => 传入文件解析器: EmbeddedValueResolverAware.setEmbeddedValueResolver()
2021-05-14 14:37:37.137 [11] => 传入资源加载器: ResourceLoaderAware.setResourceLoader()
2021-05-14 14:37:37.137 [12] => 传入事件发布器: ApplicationEventPublisherAware.setApplicationEventPublisher()
2021-05-14 14:37:37.137 [13] => 传入语言国际化: MessageSourceAware.setMessageSource()
2021-05-14 14:37:37.137 [14] => 传入应用上下文: ApplicationContextAware.setApplicationContext()
2021-05-14 14:37:37.137 [15] => 初始化前: InstantiationAwareBeanPostProcessor.postProcessBeforeInitialization()
2021-05-14 14:37:37.137 [16] => 构造之后: @PostConstruct postConstruct()
2021-05-14 14:37:37.137 [17] => 初始化: InitializingBean.afterPropertiesSet()
2021-05-14 14:37:37.138 [18] => 自定义初始化: UserService.initMethod()
2021-05-14 14:37:37.138 [19] => 初始化后: InstantiationAwareBeanPostProcessor.postProcessAfterInitialization()
2021-05-14 14:37:37.140 [20] => 初始化后: BeanPostProcessor.postProcessAfterInitialization()
2021-05-14 14:37:37.153 [21] => 动态代理: Proxy.newProxyInstance()
2021-05-14 14:37:37.153 [22] => 业务逻辑: UserInterface.test() KHighness
2021-05-14 14:37:37.154 [23] => 销毁之前: @PreDestroy preDestroy()
2021-05-14 14:37:37.154 [24] => 销毁bean: DisposableBean.destroy()
2021-05-14 14:37:37.154 [25] => 自定义销毁: UserService.destroyMethod()

总结

  • 实例化
    1. 实例化前:BeanFactoryPostProcessor#postProcessBeanFactory()
    2. 实例化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation()
    3. 执行bean的构造函数
    4. 实例化后:InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation()
    5. 为bean注入属性
  • Bean接口回调
    1. 传入bean名称:BeanNameAware#setBeanName()
    2. 传入bean类加载器:BeanClassLoaderAware#setBeanClassLoader()
    3. 传入bean工厂:BeanFactoryAware#setBeanFactory()
  • Spring接口回调
    1. 传入运行时环境:EnvironmentAware#setEnvironment()
    2. 传入文件解析器:EmbeddedValueResolverAware#setEmbeddedValueResolver()
    3. 传入资源加载器:ResourceLoaderAware#setResourceLoader()
    4. 传入事件发布器:ApplicationEventPublisherAware#setApplicationEventPublisher()
    5. 传入语言国家化:MessageSourceAware#setMessageSourceAware()
    6. 传入应用上下文:ApplicationContextAware#setApplicaionAware()
  • 初始化
    1. 初始化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInitialization()
    2. 构造之后:@PostConstruct标注的方法
    3. 初始化:InitializingBean#afterPropertiesSet()
    4. 自定义初始化:bean指定的initMethod
    5. 初始化后:InstantiationAwareBeanPostProcessor#postProcessAfterIntialization()
    6. 初始化后:BeanPostProcessor#postProcessAfterInitialization()
  • 销毁
    1. 销毁之前:@PreDestroy标注的方法
    2. 销毁bean:DisposableBean#destroy()
    3. 自定义销毁:bean指定的destroyMethod

参考

[1] 🚀 深究Spring中Bean的生命周期:https://www.cnblogs.com/javazhiyin/p/10905294.html
[2] 🚢 Spring Bean的生命周期:https://www.cnblogs.com/zrtqsk/p/3735273.html