Spring(八) Bean生命周期
参考文献
-
Spring系列-路人甲Java
普通Java对象实例化过程
- Java源码被编译为class文件;
- 等到类需要被初始化时(比如说new,反射等);
- class文件被虚拟机通过类加载器加载到JVM;
- 初始化对象供我们使用;
Spring Bean生命周期13个环节
-
阶段1: BeanDefinition配置阶段
- 是指在Spring IoC容器中注册一个BeanDefinition对象,而不是Bean的定义本身
- Bean信息定义4中方式
- API的方式
- XML的当时
- Properties文件的方式
- 注解方式
-
阶段2: BeanDefinition注册阶段
-
阶段3: BeanDefinition对象解析阶段
- BeanDefinition对象的解析主要有3种方式
- XML文件定义Bean的解析:
XmlBeanDefinitionReader
- Properties文件定义Bean的解析:
PropertiesBeanDefinitionReader
- 注解方式定义Bean的解析:
AnnotatedBeanDefinitionReader
-
阶段4: BeanDefinition合并阶段
-
阶段5: Bean Class加载阶段
-
☆阶段6: Bean实例化阶段(2个小阶段)
-
Bean实例化前阶段
-
Bean实例化中阶段
-
☆阶段7: Bean属性赋值阶段(3个小阶段)
-
Bean实例化后阶段
-
Bean属性赋值前阶段
-
Bean属性赋值阶段
-
☆阶段8: Bean Aware接口回调阶段
-
☆阶段9: Bean初始化阶段(3个小阶段)
-
Bean初始化前阶段
-
Bean初始化阶段
-
Bean初始化后阶段
-
阶段10: 所有单例bean初始化完成后阶段
-
阶段11: Bean的使用阶段
-
阶段12 :Bean销毁前阶段
-
阶段13 :Bean销毁阶段
BeanDefinition
-
Spring容器启动的过程中,会将Bean解析成Spring内部的
BeanDefinition
结构1
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {//略}
AttributeAccessor
接口:属性访问接口BeanMetadataElement
接口: BeanMetadataElement接口中有个getSource
方法返回的是BeanDefinition
定义的来源.如通过XML定义的BeanDefinition
,此时getSource
就表示定义Bean的XML资源.
-
RootBeanDefinition
类: 表示根bean定义信息- 通常bean中没有父bean的就使用这种表示
-
ChildBeanDefinition
类: 表示子bean定义信息- 如果需要指定父bean的,可以使用ChildBeanDefinition来定义子bean的配置信息,里面有个parentName属性,用来指定父bean的名称。
-
GenericBeanDefinition
类: 通用的bean定义信息- 既可以表示没有父bean的bean配置信息,也可以表示有父bean的子bean配置信息,这个类里面也有parentName属性,用来指定父bean的名称。
-
ConfigurationClassBeanDefinition
类: 表示通过配置类中@Bean方法定义bean信息- 可以通过配置类中使用@Bean来标注一些方法,通过这些方法来定义bean,这些方法配置的bean信息最后会转换为ConfigurationClassBeanDefinition类型的对象
-
AnnotatedBeanDefinition
接口: 表示通过注解的方式定义的bean信息 -
BeanDefinitionBuilder
: 构建BeanDefinition
的工具类
BeanDefinitionBuilder
使用
1 |
|
1 |
|
1 |
|
通过api设置(Map、Set、List)属性
1 | import java.util.List; |
1 |
|
- RuntimeBeanReference:用来表示bean引用类型,类似于xml中的ref
- ManagedList:属性如果是List类型的,t需要用到这个类进行操作,这个类继承了ArrayList
- ManagedSet:属性如果是Set类型的,t需要用到这个类进行操作,这个类继承了LinkedHashSet
- ManagedMap:属性如果是Map类型的,t需要用到这个类进行操作,这个类继承了LinkedHashMap
Properties
文件的方式
1 | employee.(class)=MyClass // 等同于:<bean class="MyClass" /> |
Spring Bean
的完整生命周期
1 | public class XmlDependencyConstructorInjectionDemo { |
Spring BeanDefinition
配置阶段
面向资源 BeanDefinitionReader
1 | /* |
XML配置: XMLBeanDefinitionReader
1 | // org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory |
Properties配置: PropertiesBeanDefinitionReader
1 | /** |
面向API
-
通过编写Java代码的方式定义
BeanDefinition
,使用的是Spring的BeanDefinitionBuilder
和GenericBeanDefinition
等API类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 通过BeanDefinitionBuilder创建BeanDefinition
BeanDefinition beanDefinition = BeanDefinitionBuilder
.genericBeanDefinition(User.class)
.addPropertyValue("id", 1L)
.addPropertyValue("name", "Alice")
.getBeanDefinition();
// 注册BeanDefinition
context.registerBeanDefinition("user", beanDefinition);
context.refresh();
// 获取Bean
User user = context.getBean("user", User.class);
System.out.println(user.getId() + ", " + user.getName()); // 输出:1, Alice
context.close();
Spring BeanDefinition
注册阶段
1 | // ==> org.springframework.beans.factory.xml.XmlBeanDefinitionReader#doLoadBeanDefinitions |
1 | // ==> org.springframework.beans.factory.xml.XmlBeanDefinitionReader#registerBeanDefinitions |
1 | // ==> org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#registerBeanDefinitions |
Spring BeanDefinition
解析阶段
-
面向资源
BeanDefinition
解析-
XML解析器:
BeanDefinitionParser
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
// org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseBeanDefinitions
/**
* Parse the elements at the root level in the document:
* "import", "alias", "bean".
* @param root the DOM root element of the document
*/
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
// 解析默认标签
parseDefaultElement(ele, delegate);
}
else {
// 解析自定义标签
delegate.parseCustomElement(ele);
}
}
}
}
else {
// 解析自定义标签
delegate.parseCustomElement(root);
}
}
// org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseCustomElement(org.w3c.dom.Element)
public BeanDefinition parseCustomElement(Element ele) {
return parseCustomElement(ele, null);
}
/**
* 1. 创建一个需要扩展的组件
* 2. 定义一个XSD文件描述组件内容
* 3. 创建一个文件,实现BeanDefinitionParser接口,用来解析XSD文件中定义和组件定义
* 4. 创建一个Handler文件,扩展自NamespaceHandlerSupport,目的是将组件注册到Spring容器
* 5. 编写Spring.handlers和Spring.schemas文件
* @param containingBd 父类bean,对顶层元素的解析设置为null
*/
public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
// 获取对应命名空间
String namespaceUri = getNamespaceURI(ele);
// 根据命名空间找到对应的NamespaceHandler
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
// 调用自定义的NamespaceHandler进行解析
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
// org.springframework.beans.factory.xml.NamespaceHandlerSupport#parse
/**
* Parses the supplied {@link Element} by delegating to the {@link BeanDefinitionParser} that is
* registered for that {@link Element}.
*/
public BeanDefinition parse(Element element, ParserContext parserContext) {
// 寻找解析器并进行解析操作 BeanDefinitionParser#parse
return findParserForElement(element, parserContext).parse(element, parserContext);
}
/**
* Locates the {@link BeanDefinitionParser} from the register implementations using
* the local name of the supplied {@link Element}.
*/
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
// 获取元素名称,也就是<myname:user中的user,若在示例中,此时localName为user
String localName = parserContext.getDelegate().getLocalName(element);
// 根据user找到对应的解析器,也就是在
// registerBeanDefinitionParser("user",new UserBeanDefinitionParser());
// 注册的解析器
BeanDefinitionParser parser = this.parsers.get(localName);
if (parser == null) {
parserContext.getReaderContext().fatal(
"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
}
return parser;
}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/**
* Interface used by the {@link DefaultBeanDefinitionDocumentReader} to handle custom,
* top-level (directly under {@code <beans/>}) tags.
*
* <p>Implementations are free to turn the metadata in the custom tag into as many
* {@link BeanDefinition BeanDefinitions} as required.
*
* <p>The parser locates a {@link BeanDefinitionParser} from the associated
* {@link NamespaceHandler} for the namespace in which the custom tag resides.
*
* @author Rob Harrop
* @since 2.0
* @see NamespaceHandler
* @see AbstractBeanDefinitionParser
*/
public interface BeanDefinitionParser {
/**
* Parse the specified {@link Element} and register the resulting
* {@link BeanDefinition BeanDefinition(s)} with the
* {@link org.springframework.beans.factory.xml.ParserContext#getRegistry() BeanDefinitionRegistry}
* embedded in the supplied {@link ParserContext}.
* <p>Implementations must return the primary {@link BeanDefinition} that results
* from the parse if they will ever be used in a nested fashion (for example as
* an inner tag in a {@code <property/>} tag). Implementations may return
* {@code null} if they will <strong>not</strong> be used in a nested fashion.
* @param element the element that is to be parsed into one or more {@link BeanDefinition BeanDefinitions}
* @param parserContext the object encapsulating the current state of the parsing process;
* provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}
* @return the primary {@link BeanDefinition}
*/
BeanDefinition parse(Element element, ParserContext parserContext);
}
==> 实现类
public abstract class AbstractBeanDefinitionParser implements BeanDefinitionParser {
...
public final BeanDefinition parse(Element element, ParserContext parserContext) {
AbstractBeanDefinition definition = parseInternal(element, parserContext);
if (definition != null && !parserContext.isNested()) {
try {
String id = resolveId(element, definition, parserContext);
if (!StringUtils.hasText(id)) {
parserContext.getReaderContext().error(
"Id is required for element '" + parserContext.getDelegate().getLocalName(element)
+ "' when used as a top-level tag", element);
}
String[] aliases = null;
if (shouldParseNameAsAliases()) {
String name = element.getAttribute(NAME_ATTRIBUTE);
if (StringUtils.hasLength(name)) {
aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
}
}
// 将AbstractBeanDefinition转换为BeanDefinitionHolder并注册
BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
registerBeanDefinition(holder, parserContext.getRegistry());
if (shouldFireEvents()) {
// 需要通知监听器进行处理
BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
postProcessComponentDefinition(componentDefinition);
parserContext.registerComponent(componentDefinition);
}
}
catch (BeanDefinitionStoreException ex) {
String msg = ex.getMessage();
parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
return null;
}
}
return definition;
}
...
}
-
-
面向注解BeanDefinition解析: AnnotatedBeanDefinitionReader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package com.holelin.readsource;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
public class AnnotatedBeanDefinitionReaderDemo {
public static void main(String[] args) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
AnnotatedBeanDefinitionReader beanDefinitionReader = new AnnotatedBeanDefinitionReader(beanFactory);
int beanDefinitionCountBefore = beanFactory.getBeanDefinitionCount();
beanDefinitionReader.register(AnnotatedBeanDefinitionReaderDemo.class);
int beanDefinitionCountAfter = beanFactory.getBeanDefinitionCount();
System.out.println("已加载 BeanDefinition 数量: " + (beanDefinitionCountAfter - beanDefinitionCountBefore));
AnnotatedBeanDefinitionReaderDemo demo = beanFactory.getBean("annotatedBeanDefinitionReaderDemo", AnnotatedBeanDefinitionReaderDemo.class);
System.out.println(demo);
}
}
Spring BeanDefinition
合并阶段
BeanDefinition合并
- 父子BeanDefinition合并: Root BeanDefinition不需要合并,没有parent; GenericBeanDefinition(普通BeanDefinition)
- 当前BeanFactory查找
- 层次性BeanFactory查找
1 | // org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean |
1 | // 路径 org.springframework.beans.factory.support.AbstractBeanFactory#getMergedBeanDefinition(java.lang.String) |
1 | // 路径: org.springframework.beans.factory.support.AbstractBeanFactory#getMergedLocalBeanDefinition |
1 | // 路径: org.springframework.beans.factory.support.AbstractBeanFactory#getMergedBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.config.BeanDefinition) |
Spring Bean Class 加载阶段
-
ClassLoader 类加载
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// 锁定class,根据设置的class属性或者根据className来解析Class
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
// ... 省略
}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// ==> org.springframework.beans.factory.support.AbstractBeanFactory#resolveBeanClass
/**
* Resolve the bean class for the specified bean definition,
* resolving a bean class name into a Class reference (if necessary)
* and storing the resolved Class in the bean definition for further use.
* @param mbd the merged bean definition to determine the class for
* @param beanName the name of the bean (for error handling purposes)
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the resolved bean class (or {@code null} if none)
* @throws CannotLoadBeanClassException if we failed to load the class
*/
protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
public Class<?> run() throws Exception {
return doResolveBeanClass(mbd, typesToMatch);
}
}, getAccessControlContext());
}
else {
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}
Spring Bean 实例化阶段
前阶段
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[]) |
中阶段
-
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
-
实例化方式
-
传统实例化方式
-
实例化策略:
org.springframework.beans.factory.support.InstantiationStrategy
-
-
构造器依赖注入
-
1 | /** |
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance |
合并后的BeanDefinition
处理
1 | protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args) |
1 | /** |
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
在postProcessMergedBeanDefinition
方法中对@Autowired、@Value
标注的方法、字段进行缓存org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
在postProcessMergedBeanDefinition
方法中对@Resource
标注的字段、@Resource
标注的方法、@PostConstruct
标注的字段、@PreDestroy
标注的方法进行缓存
实例化**instantiateBean
**
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean |
- autowireConstructor
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireConstructor |
1 | /** |
后阶段
判断是否要进行populate属性赋值
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
注:Bean已经实例化,但属性尚未赋值
1 | /** |
1 | /** |
Spring Bean 属性赋值阶段
-
Bean属性值元信息
PropertyValues
-
Bean属性赋值前回调
-
Spring1.2-5.0: org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessPropertyValues
-
Spring 5.1: org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties
-
1 | protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args) |
1 | /** |
1 | // org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties |
- 两个实现类
AutowiredAnnotationBeanPostProcessor
在这个方法中对@Autowired
、@Value
标注的字段、方法注入值。CommonAnnotationBeanPostProcessor
在这个方法中对@Resource
标注的字段和方法注入值。
1 | DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); |
Spring Bean Aware
接口回调阶段
-
Spring Aware
接口BeanNameAware
BeanClassLoaderAware
BeanFactoryAware
-
属于
ApplicationContext
中的生命周期中prepareBeanFactory
EnvironmentAware
EmbeddedValueResolverAware
ResourceLoaderAware
ApplicationEventPublisherAware
MessageSourceAware
ApplicationContextAware
1 | /** |
1 | // org.springframework.context.support.ApplicationContextAwareProcessor#invokeAwareInterfaces |
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition) |
Spring Bean 初始化阶段
前阶段
- 方法回调: org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
- 这个接口有2个实现类,比较重要:
org.springframework.context.support.ApplicationContextAwareProcessor
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization |
-
@PostConstruct
标准方法依赖注解驱动,通过CommonAnnotationBeanPostProcessor
添加1
2
3
4
5
6
7
8
9
10
11
12
13// org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#CommonAnnotationBeanPostProcessor
/**
* Create a new CommonAnnotationBeanPostProcessor,
* with the init and destroy annotation types set to
* {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy},
* respectively.
*/
public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);
setInitAnnotationType(PostConstruct.class);
setDestroyAnnotationType(PreDestroy.class);
ignoreResourceType("javax.xml.ws.WebServiceContext");
}
中阶段
-
Bean 初始化
(Initialization
) invokeInitMethods -
实现
InitializingBean
接口的afterPropertiesSet()
方法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/**
* Interface to be implemented by beans that need to react once all their properties
* have been set by a {@link BeanFactory}: e.g. to perform custom initialization,
* or merely to check that all mandatory properties have been set.
*
* <p>An alternative to implementing {@code InitializingBean} is specifying a custom
* init method, for example in an XML bean definition. For a list of all bean
* lifecycle methods, see the {@link BeanFactory BeanFactory javadocs}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see DisposableBean
* @see org.springframework.beans.factory.config.BeanDefinition#getPropertyValues()
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getInitMethodName()
*/
public interface InitializingBean {
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
* <p>This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set.
* @throws Exception in the event of misconfiguration (such as failure to set an
* essential property) or if initialization fails for any other reason
*/
void afterPropertiesSet() throws Exception;
} -
自定义初始化方法
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/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
// 回调方法
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 回调方法
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
后阶段
- 方法回调: org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
1 | // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization |
Spring Bean 初始化完成阶段
-
方法回调:
-
Spring 4.1+ :
org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
-
通常在
Spring ApplicationContext
使用org.springframework.beans.factory.config.ConfigurableListableBeanFactory#preInstantiateSingletons()
-
1 | /** |
Spring Bean 销毁前阶段
-
轮询beanPostProcessors列表,如果是DestructionAwareBeanPostProcessor这种类型的,会调用其内部的org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor#postProcessBeforeDestruction方法
-
在容器中被销毁
Spring Bean 销毁阶段
-
Bean销毁(Destory)
-
@PerDestory
标准方法 -
实现org.springframework.beans.factory.DisposableBean#destroy
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/**
* Interface to be implemented by beans that want to release resources on destruction.
* A {@link BeanFactory} will invoke the destroy method on individual destruction of a
* scoped bean. An {@link org.springframework.context.ApplicationContext} is supposed
* to dispose all of its singletons on shutdown, driven by the application lifecycle.
*
* <p>A Spring-managed bean may also implement Java's {@link AutoCloseable} interface
* for the same purpose. An alternative to implementing an interface is specifying a
* custom destroy method, for example in an XML bean definition. For a list of all
* bean lifecycle methods, see the {@link BeanFactory BeanFactory javadocs}.
*
* @author Juergen Hoeller
* @since 12.08.2003
* @see InitializingBean
* @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName()
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
* @see org.springframework.context.ConfigurableApplicationContext#close()
*/
public interface DisposableBean {
/**
* Invoked by the containing {@code BeanFactory} on destruction of a bean.
* @throws Exception in case of shutdown errors. Exceptions will get logged
* but not rethrown to allow other beans to release their resources as well.
*/
void destroy() throws Exception;
} -
自定义销毁方法
-
Spring Bean 垃圾收集
-
Bean垃圾回收
-
关闭Spring容器(应用上下文)
-
执行GC
-
SpringBean覆盖finalize()方法被回调
-
结合容器内Spring生命周期
-
org.springframework.context.support.AbstractApplicationContext#refresh
(入口) -
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization
(初始化单例对象入口) -
org.springframework.beans.factory.config.ConfigurableListableBeanFactory#preInstantiateSingletons
(初始化单例对象入口) -
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)
(万恶之源,获取并创建Bean的入口) -
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
(实际的获取并创建Bean的实现) -
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String)
(从缓存中尝试获取) -
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String,
org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
(实例化Bean) -
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
(实例化Bean具体实现) -
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
(具体实例化过程) -
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory
(将实例化后的Bean添加到三级缓存) -
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
(实例化后属性注入) -
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
(初始化入口)