AbstractApplicationContext类的invokeBeanFactoryPostProcessors方法把所有bean变成了beanDefinition,然后在finishBeanFactoryInitialization方法中完成实例化。
实例化过程只分析单例
1.DefaultListableBeanFactory#preInstantiateSingletons方法
这个方法的功能就是遍历beanDefinitionNames,通过getbean方法,实例化所有beanDefinition,放到beanfactory的registeredSingletons属性中。mapper接口和其他bean两种处理逻辑。
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
//遍历所有beanDefinition
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//1.mapper接口的beanDefinition的classType就是MapperFactoryBean类型,会进入这里的判断
if (isFactoryBean(beanName)) {
//这里获取bean时传入bean的名称 并且加了前缀 后面有用 前缀是&
//关键1:这个方法很重要需要深入研究
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
//默认FactoryBean延迟创建bean,所以正常情况下下面判断都不会进,也就是mapper接口默认是不进行实例化的
//如果想在这里实例化
//1.实现 FactoryBean 的子接口 SmartFactoryBean
//并重写isEagerInit方法 返回true(MapperFactoryBean没有实现)
//2.实现 InitializingBean 接口并且在 afterPropertiesSet 方法中创建 bean
//(MapperFactoryBean实现接口了,重写方法了,但是没有创建bean)
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
//2.其他 controller service之类的走这个方法
else {
//关键
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
1.1 关键:AbstractBeanFactory#getBean方法
调用doGetBean方法
这个方法的功能就是实例化所有bean。调用createBean方法创建bean及bean中注入的bean;调用getSingleton将创建的bean放到beanFactory的registeredSingletons属性中;调用getObjectForBeanInstance完成mapper接口的代理对象mapperProxy的创建。
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
//解析beanName 因为名字是可能带&前缀的 需要去掉 但是在调用getObjectForBeanInstance时需要用原始名字,需要根据&判断是否真的需要实例化mapper接口 带&就不进行实例化
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//先从缓存获取 可以先不考虑 假装它为空
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 确保当前bean依赖的bean已经实例化了,通过递归来实现
//实现方式是在类上加注解@DependsOn(value = {"dependsOnBeanB"})
//表明当前类需要在Bean dependsOnBeanB创建完成之后才能创建自己
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//这里开始创建bean
if (mbd.isSingleton()) {
//重要1 获取bean
//这里传入了lambda表达式
//public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) ObjectFactory是一个函数式接口 里面有个getObject方法,也就是 getSingleton中的singletonObject = singletonFactory.getObject()方法执行时会执行lambda表达式的内容,即创建bean
//lambda表达式的内容相当于重写了接口方法,因为是函数式接口,
//只有一个方法所以可以省略方法名,所以在getSingleton方法中
//singletonFactory.getObject()方法执行时会执行lambda表达式的内容
//这里涉及循环依赖的问题 需要单独分析
sharedInstance = getSingleton(beanName, () -> {
try {
//重要2 创建bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
//重要3 实例化mapper接口
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
1.1.1 重要1 DefaultSingletonBeanRegistry#getSingleton
将createBean方法创建的bean放到beanFactory的registeredSingletons属性中
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
//锁住singletonObjects
synchronized (this.singletonObjects) {
// 首先检查对应的bean是否已经加载过,因为singleton模式就是复用已创建的bean,所以这一步是必须的
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//获取到createBean创建的bean 如果是mapper 这里是mapperFactoryBean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
//添加到registeredSingletons中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
1.1.2 重要2 AbstractAutowireCapableBeanFactory#createBean
调用doCreateBean创建bean
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// 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);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//创建bean 这里如果是mapper接口的话 会创建一个mapperFactoryBean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
1.1.3 重要3 AbstractBeanFactory#getObjectForBeanInstance
这个方法是为mapper接口实例化服务的
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
//如果name是&开头的 则直接返回(也就是在preInstantiateSingletons调用getbean时,
//传入的就是&开头的beanname)
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
//如果是service controller这里也直接返回了
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
//能到这里是service依赖mapper时,在createBean时 populateBean方法中去实例化mapper
//最终调用mapperFactoryBean的getObject方法获取代理对象
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
总结:
情况1:实例化mapper接口,此接口未被service注入
只会把MapperFactoryBean加到beanFactory的registeredSingletons属性中,并不会调用MapperFactoryBean的getObject方法创建代理对象mapperProxy。
DefaultListableBeanFactory#preInstantiateSingletons
这里调用getBean时给beanName加了前缀 &,然后在执行doGetBean时执行createBean方法时会创建当前mapper对应的MapperFactoryBean类型及getSingleton方法把MapperFactoryBean加到beanFactory的registeredSingletons属性中,然后执行getObjectForBeanInstance方法
AbstractBeanFactory#doGetBean
AbstractBeanFactory#getObjectForBeanInstance
name加了前缀&,直接返回当前bean
情况2:实例化mapper接口,此接口被service注入
在实例化service时会实例化mapper接口
DefaultListableBeanFactory#preInstantiateSingletons
AbstractBeanFactory#getBean(java.lang.String)
AbstractBeanFactory#doGetBean
在getSingleton中会执行singletonObject = singletonFactory.getObject()方法,然后执行lambda表达式中的createBean方法
DefaultSingletonBeanRegistry#getSingleton
AbstractAutowireCapableBeanFactory#createBean
AbstractAutowireCapableBeanFactory#doCreateBean
在populateBean方法中会实例化注入的mapper接口
AbstractAutowireCapableBeanFactory#populateBean
AutowiredAnnotationBeanPostProcessor#postProcessProperties
InjectionMetadata#inject
AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
DefaultListableBeanFactory#resolveDependency
DefaultListableBeanFactory#doResolveDependency
DependencyDescriptor#resolveCandidate
这里再次调用getbean方法,传入mapper名字
AbstractBeanFactory#doGetBean
在执行doGetBean时执行getSingleton及createBean方法时会创建当前mapper对应的MapperFactoryBean类型
然后执行getObjectForBeanInstance方法会实例化mapper,也就是创建mapper的代理对象
AbstractAutowireCapableBeanFactory#getObjectForBeanInstance
AbstractBeanFactory#getObjectForBeanInstance
这里根据名字就能看出来 getObjectFromFactoryBean 通过FactoryBean获取对象
FactoryBeanRegistrySupport#getObjectFromFactoryBean
FactoryBeanRegistrySupport#doGetObjectFromFactoryBean
通过MapperFactoryBean的getObject方法实例化mapper
MapperFactoryBean#getObject
这里的获取就是创建代理对象mapperProxy
情况3:实例化service,controller
前面和情况2一致,情况2在doCreateBean方法中执行完populateBean方法后把注入的bean(mapper)实例化完成后执行initializeBean方法。
AbstractAutowireCapableBeanFactory#initializeBean
1.如果当前bean实现了InitializingBean接口,则调用bean重写的afterPropertiesSet方法。在invokeInitMethods方法中
2.如果当前bean定义了InitMethod,则执行这个方法。在invokeInitMethods方法中
3.执行applyBeanPostProcessorsBeforeInitialization 在applyBeanPostProcessorsBeforeInitialization方法中。作用就是修改bean定义并返回。自己写的bean想使用这个功能就需要实现BeanPostProcessor接口,重写postProcessBeforeInitialization方法
4.执行applyBeanPostProcessorsAfterInitialization 在applyBeanPostProcessorsAfterInitialization 方法中。自己写的bean想使用这个功能就需要实现BeanPostProcessor接口,重写postProcessAfterInitialization方法
这里会获取所有的processor执行postProcessAfterInitialization方法,自己写的bean实现了BeanPostProcessor接口之后,这里就能获取到。这里是所有bean初始化之后都要执行一次,也就是所有的bean都会走我们重写的postProcessAfterInitialization或postProcessBeforeInitialization方法,注意对类型进行判断。
至此createBean方法完成,继续执行getSingleton方法,把实例化好的service放到beanFactory的registeredSingletons属性中。实例化service完成。