实例化BeanFactory中已经被注册但是未实例化的所有实例(懒加载的不需要实例化)。比如invokeBeanFactoryPostProcessors方法中根据各种注解解析出来的类,在这个时候都会被初始化。实例化的过程各种BeanPostProcessor开始起作用。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/**
* 初始化所有剩余的单例bean
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 为容器注册conversion service,用于转化属性值
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
/**
* 如果没有的话(比如PropertyPlaceholderConfigurer),注册一个默认的嵌入值解析器(value resoler)。
* 用于解析通过注解导入的值。
*/
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// 实例化所有剩余的(非延迟初始化)单例对象
beanFactory.preInstantiateSingletons();
}
实例化单例对象
beanFactory.preInstantiateSingletons
调用的是DefaultListableBeanFactory.preInstantiateSingletons
:
1 | public void preInstantiateSingletons() throws BeansException { |
bean初始化
bean初始化调用的是AbstractBeanFactory.getBean
,最终调用的是AbstractBeanFactory.doGetBean
1 | protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { |
创建bean实例
创建bean实例的方法为:AbstractAutowireCapableBeanFactory.createBean
:
1 | protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { |
doCreateBean
createBean
主要的函数为doCreateBean
:
1 | protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) |
创建bean主要分为三个步骤:
- 实例化bean
- 注入成员以及变量
- 执行初始化步骤
实例化bean
实例化bean调用的是AbstractAutowireCapableBeanFactory.createBeanInstance
:
1 | protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { |
autowireConstructor
在构造函数中注入相应的参数
1 | protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs) { |
autowireConstructor
实际的工作在于寻找构造函数、参数,然后调用InstantiationStrategy.instantiate
来实例化bean。
1 | beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse); |
InstantiationStrategy.instantiate
1 | public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner, final Constructor<?> ctor, Object... args) { |
AbstractAutowireCapableBeanFactory.instantiateBean
使用默认的构造函数实例化bean
1 | /** |
实际调用的是SimpleInstantiationStrategy.instantiate
:
SimpleInstantiationStrategy.instantiate
1 | public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) { |
注入成员以及变量
bean实例化完成之后,调用AbstractAutowireCapableBeanFactory.populateBean
注入其中的成员以及变量:
1 | protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { |
- ApplicationContextAwareProcessor
- ImportAwareBeanPostProcessor
- BeanPostProcessorChecker
CommonAnnotationBeanPostProcessor
支持
@PostConstruct
、@PreDestroy
注释AutowiredAnnotationBeanPostProcessor
支持
@Autowired
、@Value
注释RequiredAnnotationBeanPostProcessor
支持
@Required
注释ApplicationListenerDetector
postProcessPropertyValues
以AutowiredAnnotationBeanPostprocessor为例,它委托给InjectionMetadata对象来完成属性注入,AutowiredAnnotationBeanPostprocessor.postProcessPropertyValues
:
1 | public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { |
InjectionMetadata.inject(Object target, String beanName, PropertryValues pvs)
1
2
3
4
5
6
7
8
9
10
11
12public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
Collection<InjectedElement> elementsToIterate = (this.checkedElements != null ? this.checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
boolean debug = logger.isDebugEnabled();
for (InjectedElement element : elementsToIterate) {
if (debug) {
logger.debug("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}InjectionMetadata.inject(Object target, String requestingBeanName, PropertyValues pvs)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable {
if (this.isField) {
Field field = (Field) this.member;
ReflectionUtils.makeAccessible(field);
field.set(target, getResourceToInject(target, requestingBeanName));
}
else {
if (checkPropertySkipping(pvs)) {
return;
}
try {
Method method = (Method) this.member;
ReflectionUtils.makeAccessible(method);
method.invoke(target, getResourceToInject(target, requestingBeanName));
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
可以看到,如果是成员变量则调用field.set
来设置变量,如果是方法则调用method.invoke
来调用方法
applyPropertyValues
注入属性值
最终调用的方法为AbstractNestablePropertyAccessor.setPropertyValue
:
1 | protected void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException { |
其中processKeyedProperty设置array、list、map三种类型的属性;processLocalProperty设置field、bean类型的属性。
field类型的属性通过DirectFieldAccessor.setValue
来设置:
1 | public void setValue(Object object, Object value) throws Exception { |
bean类型的属性通过BeanWrapperImpl.setValue
来设置:
1 | public void setValue(final Object object, Object valueToApply) throws Exception { |
bean初始化
在完成bean实例化,注入成员以及变量之后,执行bean的一系列初始化操作。包括调用init方法,执行bean post processors
。
bean初始化调用的是AbstractAutowireCapableBeanFactory.initializeBean
1 | /** |
applyBeanPostProcessorBeforeInitialization
调用beanPostProcessors中各个beanPostProcessor的postProcessBeforeInitialization方法
调用初始化方法
初始化方法为AbstractAutowireCapableBeanFactory.invokeInitMethods
:
1 | protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { |
调用自定义的初始化方法
自定义的初始化方法为AbstractAutowireCapableBeanFactory.invokeCustomInitMethod
1 | protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { |
applyBeanPostProcessorsAfterInitialization
调用beanPostProcessors中各个beanPostProcessor的postProcessAfterInitialization方法