This is the 28th day of my participation in the August Text Challenge.More challenges in August
Spring source code analysis series
- Spring source Code analysis -IOC basic concepts
- Spring source code analysis -IOC core components
- Spring Source Code Analysis -IOC source code Analysis (1)
- Spring IOC source code analysis -obtainFreshBeanFactory
- Spring IOC source analysis – invokeBeanFactoryPostProcessors (3)
- The Spring IOC source analysis – registerBeanPostProcessors (4)
- Spring IOC – finishBeanFactoryInitialization source analysis
preface
The lifecycle of a Bean is one of the most important questions in the Spring framework. The BeanFactory interface annotation describes the entire process of a Bean object from factory production to its final demise. If we don’t look at the source code, we can actually think about, what does it take for an object to be recreated to death?
We might think of creating the object first of course, instantiating it, of course, calling the constructor, and then after instantiating it, we need to do some initialization, like setting the values of some non-constructor properties, and then destroying the object when it runs out. Of course, Spring beans are different because there are Bean dependencies and an extra property population before initialization,
The life cycle of a Spring Bean is actually an object creation process that can be divided into four phases and multiple extension points
The life cycle of the Bean
The lifecycle of a Bean is described in Spring source code comments
The process of Bean destruction
The life cycle of a Spring Bean is divided into four phases and multiple extension points. Extension points can be divided into affecting multiple beans and affecting a single Bean
1.1 Four Stages
- Instantiate the Instantiation
- Property assignment Populate
- Initialize the Initialization
- Destruction of Destruction
Source analysis: the first three stages of the source code, are AbstractAutowireCapableBeanFactory # doCreateBean method.
CreateBeanInstance instantiation
The populateBean property injection and initializeBean initialize the Bean methodInstantiation of the Bean method above is the getBean () method calls, and getBean is invoked in finishBeanFactoryInitialization method, used to instantiate the singleton not lazy loading beans.
Destruction of Bean stage: is invoked when the container close, see ConfigurableApplicationContext# close ()
1.2 Lifecycle extension points
Life cycle extension points are numerous, categorized by the scope of the impact beans
1.2.1 Affecting multiple beans
- BeanPostProcessor
- InstantiationAwareBeanPostProcessor
InstantiationAwareBeanPostProcessor ACTS on the instantiation phase before and after the BeanPostProcessor function before and after the initialization phase.
1.2.2 Affecting individual Beans
1. Aware interface, divided into two groups Aware Group1 and Aware Group2
A bunch of Aware interfaces. Aware is an identifying super-interface, and beans that implement it have the ability to be notified by the Spring container through callbacks. That is, classes that directly or indirectly implement this interface have the ability to be notified by the Spring container.
1.1 Aware Group1
- BeanNameAware
- BeanClassLoaderAware
- BeanFactoryAware
Aware Group2
- EnvironmentAware
- EmbeddedValueResolverAware
- ApplicationContextAware (this interface and contains ResourceLoaderAware ApplicationEventPublisherAwareMessageSourceAware)
EmbeddedValueResolverAware available Spring EL parser, the interface of user custom annotations need to support spel expressions you can use, very convenient.
ApplicationContextAware ResourceLoaderAware,ApplicationEventPublisherAware,MessageSourceAware The return values are essentially the current ApplicationContext object, because ApplicationContext is a composite interface.
public interface ApplicationContext extends EnvironmentCapable.ListableBeanFactory.HierarchicalBeanFactory.MessageSource.ApplicationEventPublisher.ResourcePatternResolver {
/ /...
}
Copy the code
Aware extension point calls timing source code analysis
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if(System.getSecurityManager() ! =null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 1. Call Aware starting with three beans in Group1
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null| |! mbd.isSynthetic()) {// Call Aware from Group2;
// This is essentially the call point for the BeanPostProcessor
/ / and Group1 Aware of the different, this is through the BeanPostProcessor (ApplicationContextAwareProcessor).
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// Initialize method
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw newBeanCreationException( (mbd ! =null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null| |! mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); }return wrappedBean;
}
Copy the code
2. Life cycle
- InitializingBean
- DisposableBean
InitializingBean, as its name implies, is the interface associated with initializing beans.
The afterPropertiesSet() method is called during initialization. InitializingBean corresponds to the initialization phase of the lifecycle. InvokeInitMethods (beanName, wrappedBean, MBD) of the source code above; Method.
There are three ways to implement the specified initialization method:
-
Use the @postconstruct annotation, which applies to the void method
-
Configure the init-method method in the configuration file
<bean id="User" class="com.br.spring.demo.dto.User" init-method="init2">
<property name="name" value="boren"></property>
</bean>
Copy the code
- Implement the InitializingBean interface
@Component
public class UserBean implements InitializingBean {
private String name;
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
//1. Use the PostConstruct annotation
@PostConstruct
public void init(a){
System.out.println("Execute init method");
}
//2. Configure init-method in the XML configuration file
public void init2(a){
System.out.println("Execute init2 method");
}
//3. Implement InitializingBean interface
public void afterPropertiesSet(a) throws Exception {
System.out.println("Execute init3 method"); }}Copy the code
The last
The four stages of the Spring life cycle, instantiation, property injection, initialization, destruction, and Spring core extension point Aware and lifecycle interface InitializingBean, DisposableBean