在Spring容器中初始化一些国际化相关的属性。
在Spring容器中初始化事件广播器,事件广播器用于事件的发布。
一个模板方法,不同的Spring容器做不同的事情。
比如web程序的容器AnnotationConfigEmbeddedWebApplicationContext中会调用createEmbeddedServletContainer方法去创建内置的Servlet容器,如启动tomcat。
把Spring容器内的时间监听器和BeanFactory中的时间监听器都添加的事件广播器中。
实例化BeanFactory中已经被注册但是未实例化的所有非懒加载实例
主流程
主流程大致为,从缓存中找到是否已经实例化了该 singleton bean,如果已经实例化好了,那么就直接返回;如果在缓存中没有找到,则将当前的 bean 封装为 RootBeanDefinition,然后通过调用 DefaultSingletonBeanRegistry#getSingleton 得到初始化好的 singleton bean,然后将其注册至缓存,然后再判断是普通 bean 还是 factory bean 作必要的处理后,最后返回。
AbstractBeanFactory#doGetBean
Object sharedInstance = getSingleton(beanName);
先从缓存中查找是否以及实例化了该bean,如果已存在,直接返回。
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
将当前bean标记为已创建。
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
//回调AbstractAutowireCapableBeanFactory 的 createBean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
这里调用DefaultSingletonBeanRegistry#getSingleton:
beforeSingletonCreation(beanName);
singletonObject = singletonFactory.getObject();
afterSingletonCreation(beanName);
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
beforeSingletonCreation和afterSingletonCreation 检查了当前bean是不是在被排除的bean集合中以及是不是正在创建。
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
而addSingleton是将实例化好的bean加入缓存
接下来重点关注singletonObject = singletonFactory.getObject(),这里回调了getObject方法,即AbstractAutowireCapableBeanFactory#createBean。通过此回调方法正式拉开了实例化 bean 的序幕。
AbstractAutowireCapableBeanFactory#createBean
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
在进行真正的实例化之前,会先调用一部分已注册的beanPostProcessor的before,after方法。
AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
可以看出,这里只处理实现了InstantiationAwareBeanPostProcessor的processor,如AbstractAutoProxyCreator,用来处理AOP。
从主流程可以看出主要做了三件事:一、create Bean Instance;二、populate bean;三、initialize bean。
createBeanInstance
根据 bean 的不同配置方式,实现了三种实例化bean的方式,分别是 factory instantiate bean
、autwire instantiate bean
以及 default instantiate bean
。
AbstractAutowireCapableBeanFactory#createBeanInstance
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
...
if (mbd.getFactoryMethodName() != null) {
//使用factory method实例化bean
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
...
//如果已经解析过则使用解析好的构造函数方法不需要再次解析
if (resolved) {
if (autowireNecessary) {
//constructor自动注入
return autowireConstructor(beanName, mbd, null, null);
}
else {
//默认构造方法实例化
return instantiateBean(beanName, mbd);
}
}
//未解析过,解析构造方法,返回数组。这里的数组包含显示声明的无参构造
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//使用构造方法实例化
return autowireConstructor(beanName, mbd, ctors, args);
}
...
// 没有特殊的处理,只需使用no-arg构造函数即编译器提供的无参构造
return instantiateBean(beanName, mbd);
}
分别看一下每个实例化过程
使用factoryMethod比较简单,找到factory method,反射调用即可。
ConstructorResolver#instantiate
//AbstractAutowireCapableBeanFactory#instantiateUsingFactoryMethod
protected BeanWrapper instantiateUsingFactoryMethod(String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}
//#ConstructorResolver#instantiateUsingFactoryMethod
public BeanWrapper instantiateUsingFactoryMethod(String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, factoryMethodToUse, argsToUse));
}
//#instantiate
private Object instantiate(String beanName, RootBeanDefinition mbd,@Nullable Object factoryBean, Method factoryMethod, Object[] args) {
...
return this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, this.beanFactory, factoryBean, factoryMethod, args);
}
可以看出调用链很长,最后调用了一个Instantiation的策略来实例化。默认的实现是SimpleInstantiationStrategy。
SimpleInstantiationStrategy#instantiate
...
Object result = factoryMethod.invoke(factoryBean, args);
if (result == null) {
result =
new NullBean();
}
...
return result;
通过反射调用factoryMethod实例化bean
接上文的AbstractAutowireCapableBeanFactory#createBeanInstance
方法。
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
这里会解析并返回显示声明的构造方法数组。解析过程会调用BeanPostProcessor#determineCandidateConstructors
,这部分主要是由AutowiredAnnotationBeanPostProcessor
来处理
AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors
由于代码太长,节选部分代码
//获取所有构造方法
Constructor<?>[] rawCandidates= beanClass.getDeclaredConstructors();
for (Constructor<?> candidate : rawCandidates) {
//获取指定类中指定注解
AnnotationAttributes ann = findAutowiredAnnotation(candidate);
if (ann != null) {
//如果在此构造方法之前已有requiredConstructor,则报错
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
//获取注解中required属性值
boolean required = determineRequiredStatus(ann);
if (required) {
//如果候选构造方法集合不为空
if (!candidates.isEmpty()) {
throw new BeanCreationException;
}
//当前的构造方法就是required属性所配置的构造方法
requiredConstructor = candidate;
}
//将当前的构造方法添加到候选构造方法集合中
candidates.add(candidate);
}
//如果类中没有指定注解,并且构造方法参数列表为空
else if (candidate.getParameterCount() == 0) {
//当前的构造方法是默认构造方法
defaultConstructor = candidate;
}
//如果候选构造方法集合不为空
if (!candidates.isEmpty()) {
// Add default constructor to list of optional constructors, as fallback.
if (requiredConstructor == null) {
//如果所有的构造方法都没有配置required属性,且有默认构造方法
if (defaultConstructor != null) {
//将默认构造方法添加到候选构造方法列表
candidates.add(defaultConstructor);
}
//...
}
//将候选构造方法集合转换为数组
candidateConstructors = candidates.toArray(new Constructor<?>[0]);
}
//如果候选构造方法只有1个且有参数
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
//则当前构造方法就是候选类的构造方法
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
//...
else {
//其他情况下返回一个空的数组,比如有多个构造方法的情况下
candidateConstructors = new Constructor<?>[0];
}
//将类的候选构造方法集合存放到容器的缓存中
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
//返回指定类的候选构造方法数组,如果没有返回null
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
if (ao.getAnnotations().length > 0) { // autowiring annotations have to be local
//遍历所有autowire相关的注解:@Autowire、@Value以及JSR-330等
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
//获取给定对象上的指定类型的注解
AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
if (attributes != null) {
return attributes;
}
}
}
return null;
}
public class A{
private final B b;
public A(B b){
this.b=b;
}
}
No default constructor found
。如果解析出的构造方法不为空,则使用返回的构造方法实例化。
protected BeanWrapper autowireConstructor(
String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
ConstructorResolver#autowireConstructor
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
//节选部分
//这里省略了从缓存中获取,以及将构造方法list按参数个数排序
for (Constructor<?> candidate : candidates) {
if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
//如果已找到选用的构造函数或者需要的参数个数小于当前构造函数的参数个数则终止,因为已经按照参数个数降序排列
break;
}
ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
if (resolvedValues != null) {
//...
//在给定已解析的构造函数参数值的情况下,创建一个参数数组以调用构造函数或工厂方法。调用getBean获取参数
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes,paramNames,getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousConstructors = null;
}
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
}
}
需要注意的一点是createArgumentArray()
,这个方法会调用resolveAutowiredArgument()
,之后会调用beanFactory.resolveDependency()
去解析依赖关系,然后调用getBean来获取实例。详见 @Autowired详解的解析依赖关系
这里的实例化也由SimpleInstantiationStrategy
完成的。
SimpleInstantiationStrategy#instantiate
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,final Constructor<?> ctor, Object... args) {
return BeanUtils.instantiateClass(ctor, args);
}
//instantiateClass
ctor.newInstance(args);
//newInstance
T inst = (T) ca.newInstance(initargs);
也是通过使用其构造函数 constructor 使用Java 反射实例化了 bean。
AbstractAutowireCapableBeanFactory#instantiateBean
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
SimpleInstantiationStrategy#instantiate
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse= clazz.getDeclaredConstructor();
}
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
//instantiateClass
ctor.newInstance(args);
//newInstance
T inst = (T) ca.newInstance(initargs);
通过使用编译器生成的默认无参 constructor通过Java 反射实例化了 bean
这部分的初始化主要是处理依赖关系,如@Autowired、@Value、@Inject注解的属性和方法
AbstractAutowireCapableBeanFactory#populateBean
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
pvs = pvsToUse;
进行依赖注入的过程,先处理autowire的注入,可以根据Bean的名字或类型来完成Bean的autowire
if (pvs != null) {
//对属性进行注入 如@Autowired属性
applyPropertyValues(beanName, mbd, bw, pvs);
}
然后对属性进行注入。详见 @Autowired详解
这部分主要是初始化bean的自身属性,如注入Aware对象,执行afterPropertiesSet方法等。
AbstractAutowireCapableBeanFactory#initializeBean
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
invokeAwareMethods(beanName, bean); ①
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//执行bean-post-processor 的beforeInitialization方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization (wrappedBean, beanName);②
}
try {
//处理实现了InitializingBean接口的beans的回调方法
invokeInitMethods(beanName, wrappedBean, mbd);③
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//执行bean-post-processor 的afterInitialization方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);④
}
return wrappedBean;
}
整个流程可以理解为三大块
AbstractAutowireCapableBeanFactory#invokeAwareMethods
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
//将当前的beanFactory注入,这也就是为什么如果实现了BeanFactoryAware接口,会自动获取到但钱的BeanFactory实例
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
可以看到,注入了三种情况
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
可以看出如果某个 beanProcessor 处理返回一个 null 则直接返回,并且终止其余的 bean-post-processors。要注意的是,该回调方法是针对对容器中所有的普通 bean 进行的回调。并且该方法是在回调 InitializeBean 接口方法之前调用,并且是在 populate bean之后进行的调用,通常是对原有 bean 做一层封装,然后返回该封装对象。这点BeanPostProcessor接口注释也已经说明。
public interface BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given new bean instance before any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* Apply this BeanPostProcessor to the given new bean instance after any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
*
This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other BeanPostProcessor callbacks.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
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.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
.....
((InitializingBean) bean).afterPropertiesSet();
.....
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
可以看到,主要回调的是InitializingBean接口的afterPropertiesSet方法,所以,我们可以让某个 bean 实现 InitializingBean 接口,并通过该接口实现一些当 bean 实例化好以后的回调方法,注意afterPropertiesSet并不返回任何值,所以,这里不是像 bean-post-processor 那样对 bean 起到修饰的作用,而是起到纯粹的调用作用
refresh做完之后需要做的其他事情。
到这里Spring 容器的bean初始化就全部完成了,最后补充一个扩展,那就是ApplicationContext是在什么时候注入的,从上述文章不难看出,invokeAwareMethods并没有对ApplicationContext注入,经过测试发现,如果实现了ApplicationContextAware,则将会在调用 bean-post-processors 接口方法这一步的postProcessBeforeInitialization中的invokeAwareInterfaces方法进行注入
ApplicationContextAwareProcessor
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
....
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);
}
}
}
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
以上。