A, BeanDefinition
What is a BeanDefinition, which is used to define a Bean
Docs. Spring. IO/spring – fram…
The bean is created based on some configuration metadata we provide, such as XML. In the container, the metadata we configured is represented as beanDefinitions
Overview of the bean’s life cycle
1. Instantiate the bean (createBeanInstance)
This phase mainly instantiates a bean object, mainly through reflection and cglib dynamic bytecode generation object (can be thought of as a new object out).
2. Attribute Assignment (populateBean)
This stage is primarily used to assign attributes to bean objects (such as @autowired)
Consider: How does Spring solve circular dependencies
3. Initialize the bean (initializeBean)
Call org. Springframework. Beans. Factory. InitializingBean interface afterPropertiesSet () And call the init-method we specify (for example, init-method for XML, init parameter for @bean)
Thinking: is @postconstruct completed at this stage
The above three phases, which correspond to the three sections of the code, are the three phases of Bean creation
4. Use
The bean usage phase is also the business invocation phase
5. Destroy
Call the destroy method
6. Swimlane diagram for Bean life cycle (creation) :
Create a bean (InstanceBean)
From the code, we know that InstanceBeans can be instantiated in several ways
1. Instantiate by factoryBean (red box 1)
Whether to use BeanDefinition’s factoryMethod instantiation (@bean annotations are instantiated using factory methods. You can customize how they are instantiated)
2. Instantiation by parameter constructor (red box 2)
Build (beans that recursively instantiate constructor input parameters) using the autowireConstructor method
3. Instantiation via a no-parameter constructor (red box 3)
Both approaches 2 and 3 to create beans end up instantiating objects through reflection or cglib bytecode
4. Bean Creation — Attribute Assignment (PopulateBean)
As you can see, I have four red boxes, which are the two main steps of this PopulateBean
1. InstantiationAwareBeanPostProcessor instantiation rear processing (postProcessBeforeInstantiation). (Red box 1)
Since this is post-processing of the instantiation, we are talking about attribute assignment, so we will ignore this part of the code for now
2. Attribute auto-assembly initialization. (Red box 2)
This section gets the resolvedAutowireMode in BeanDefinition. Then find the set method in the bean according to the autown-mode (assemble AUTOWIRE_BY_TYPE by attribute type or AUTOWIRE_BY_NAME by attribute name) and match the corresponding attribute to find or recursively create the corresponding bean. Put it inside the PVS (PropertyValues).
1. The configuration of AutowireMode autowire mode is written in the @bean annotation’s Autowire attribute, and in the XML autowire attribute
2. In addition to the @bean annotation’s Autowire attribute, XML’s Autowire attribute is written to BeanDefinition, typically using — MyBatis, definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE)
3. If the default value is not set, the default value is AUTOWIRE_NO, that is, the automatic assembly of attributes is not implemented
4. As you can see from my description, this part of the code does not assign the property value to the bean, but only gets the property value in the PVS (PropertyValues). The assignment operation is the fourth red box
5.AutowireMode has nothing to do with @autowire
3. InstantiationAwareBeanPostProcessor attribute value (postProcessPropertyValues) processing. (Red box 3)
This part of the code is the main place for annotation injection like @Autowire
InstantiationAwareBeanPostProcessor have multiple implementation classes, code through multiple implementation classes to assembly attributes.
Such as:
- AutowiredAnnotationBeanPostProcessor implement assembly @autowired, @ Inject and @ the Value
- CommonAnnotationBeanPostProcessor assembly @ Resource, @ WebServiceRef, @ EJB
- .
4. Attribute auto-assembly assignment (red box 4)
The code that assigns the property in red box 2 to the current bean, the applyPropertyValues section
5. To summarize
Conclusion: The logic of PopulateBean is basically two
One is to assemble the attributes corresponding to the set method through the mode of automatic assembly. There are three main types
- AUTOWIRE_NO (default, no property autowiring)
- AUTOWIRE_BY_NAME (auto assemble by attribute name)
- AUTOWIRE_BY_TYPE (auto-assemble by attribute type)
Another is by cycle call InstantiationAwareBeanPostProcessor# postProcessPropertyValues method to injection of attributes, This is where @AutoWired, @Resource, @Value and other annotations are injected
Creating a bean — InitializeBean
I’ve circled four red boxes here, so we just need to focus on the third red box
- Red box 1 is used to determine whether it is BeanNameAware, BeanClassLoaderAware, or BeanFactoryAware. If it is, beanName, classLoader, and beanFactory should be injected respectively
- 2 of red box is called BeanPostProcessor# postProcessBeforeInitialization performs initialization of pre operation, here we ignore
- Red box 3 is the initialization main code, which executes the initialization method invokeInitMethods
- Red box 4 is called BeanPostProcessor# postProcessAfterInitialization performs initialization rear operations, here we ignore
Now let’s look at what’s going on in invokeInitMethods, the main method of initialization
1. Iterate through the InitializingBean#afterPropertiesSet method
Usage scenario: Policy mode +afterPropertiesSet
2. Execute the bean’s initialization method (init-method)
Bean initialization method can usually specified by annotation org. Springframework. Context. The annotation. Bean# initMethod or XML init – method attribute to specify. The logic is to invoke the change method through reflection
Summary of the three phases of bean creation
- InstanceBean
- Instantiation via factoryBean
- Instantiated by a parameterized constructor
- Instantiated by a no-argument constructor
- PopulateBean
- AutowireMode
- AUTOWIRE_NO (default, no property autowiring)
- AUTOWIRE_BY_NAME (auto assemble by attribute name)
- AUTOWIRE_BY_TYPE (auto-assemble by attribute type)
- InstantiationAwareBeanPostProcessor# postProcessPropertyValues on @autowired, @ the Resource and @ the Value attribute assignment annotation
- AutowireMode
- InitializeBean
- Execute the InitializingBean#afterPropertiesSet method
- Execute init-method (@bean #initMethod and XML init-method)
Extension points in the bean lifecycle
We divide the development sites into two categories
- The Bean’s life cycle members InitializingBean, DisposableBean
- The Bean lifecycle InstantiationAwareBeanPostProcessor, BeanPostProcessor important participants
1. The InitializingBean/DisposableBean interfaces
The InitializingBean interface corresponds to the initialization of the bean, and DisposableBean corresponds to the destruction of the bean. These two interfaces are similar, so we will only select the InitializingBean for explanation
The InitializingBean interface has only one method, afterPropertiesSet. The bean class that implements this interface can do something during the bean initialization phase.
2. The BeanPostProcessor interface
The BeanPostProcessor interface affects the bean initialization phase
It has two interfaces
- BeanPostProcessor#postProcessBeforeInitialization
- BeanPostProcessor#postProcessAfterInitialization
As the name implies, one is called before the initialization stage, and the other is called after the initialization stage. See red box 2 and red box 4 of 5
The typical use of AOP, @ PostConstruct BeanPostProcessor# postProcessAfterInitialization
3. InstantiationAwareBeanPostProcessor interface
InstantiationAwareBeanPostProcessor interface in Bean instantiation, attribute assignment, as well as the initialization phase
It has five ports in total
- InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
This is called before the bean is instantiated (InstanceBean). This is the logic before the bean is created
- InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
Call after bean instantiation (InstanceBean), call before attribute assignment (PopulateBean), call place see 4, bean creation — attribute assignment (PopulateBean) red box 1
- InstantiationAwareBeanPostProcessor#postProcessPropertyValues
Attribute assignment (PopulateBean) is one of the main logic, CommonAnnotationBeanPostProcessor implements this method to @ the properties of the Resource assignment, AutowiredAnnotationBeanPostProcessor implements this method for @ the Value, the @autowired attribute assignment, call see four, bean creation — attribute assignment (PopulateBean) red box 3
- BeanPostProcessor#postProcessBeforeInitialization
With the BeanPostProcessor
- BeanPostProcessor#postProcessAfterInitialization
With the BeanPostProcessor
8. Various interfaces for Aware
Aware interfaces fall into two main categories
1.BeanNameAware, BeanClassLoaderAware and BeanFactoryAware interfaces
The three interfaces in BeanPostProcessor# postProcessBeforeInitialization before execution, this a few interface is not involved in the creation of beans, just to get something, See 5. Bean Creation — InitializeBean in red box 1
2. Other Aware interfaces
These interfaces are not involved in the creation of Bean, is used to obtain something, through BeanPostProcessor# postProcessBeforeInitialization injection into the Bean
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
invokeAwareInterfaces(bean);
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); }}}}Copy the code
- EnvironmentAware gets the Spring configuration file
- EmbeddedValueResolverAware get Spl parser
- ApplicationContextAware (ResourceLoaderAware \ ApplicationEventPublisherAware \ MessageSourceAware) for bean object
- .
Nine,
- Three phases of creation
- Instantiation of a bean
- Instantiation via factoryBean
- Instantiate the parameterized constructor
- Instantiate the no-parameter constructor
- Bean property assignment
- Set the AutowireMode assignment
- Implement InstantiationAwareBeanPostProcessor# postProcessPropertyValues KouFu value
- Initialization of the bean
- The init-method method to run
- Run the InitializingBean#afterPropertiesSet interface
- Instantiation of a bean
- Two lifecycle interfaces
- InitializingBean#afterPropertiesSet (part of the bean’s initialization phase)
- DisposableBean#destroy (belonging to the bean’s destruction stage)
- Two lifecycle participating interfaces
- BeanPostProcessor
- PostProcessBeforeInitialization (bean initialization phase front calls)
- Rear postProcessAfterInitialization (bean initialization calls)
- InstantiationAwareBeanPostProcessor
- PostProcessAfterInstantiation (bean instantiation phase front calls)
- PostProcessBeforeInstantiation (bean instantiation phase rear calls)
- PostProcessPropertyValues (one of the bean attribute assignment)
- PostProcessBeforeInitialization (bean initialization phase front calls)
- Rear postProcessAfterInitialization (bean initialization phase calls)
- BeanPostProcessor
- A wide variety of Aware interfaces
- BeanNameAware, BeanClassLoaderAware, and BeanFactoryAware interfaces
- Aware of ApplicationContextAwareProcessor injection