1. finishBeanFactoryInitialization
谈起Bean的依赖注入,还是得承接这个refresh中的关键方法进行切入.Spring在经过加载完BeanDefinition
到BeanFactory
后,进行了BeanPostProcessor
的注册,跟着注册了事件发布器与事件监听器。在进行到finishBeanFactoryInitialization
这个方法后,Spring开始着手Bean
装配这项繁杂的工作了。简单地说,生产Bean
的材料与回调钩子已经准备就绪,Spring这个Bean工厂开始对BeanDefinition
进行实例化,并开始实行依赖注入,然后通过容器进行其生命周期的管理.
/**
* 完成此上下文的bean工厂的初始化,初始化所有剩余的单例bean。
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 类型转换器
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));
}
// 注册一个解析器,主要用来解析@Value("${xxx.xxx}")或者在xml中定义的<value = "${xxx.xxx}">的信息
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 更早地实例化LoadTimeWeaverAware beans 以便更早地注册它们的transformers.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止在prepareBeanFactory中设置的临时用作类型匹配的类加载器
beanFactory.setTempClassLoader(null);
// 缓存所有BeanDefinition元数据,不希望在之后的操作中发生变化
beanFactory.freezeConfiguration();
// 实例化剩余的所有非延迟加载的单例bean
beanFactory.preInstantiateSingletons();
}
2. preInstantiateSingletons
/**
* ApplicationContext中bean初始化的地方
* @throws BeansException
*/
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// 遍历一个副本以允许使用init方法,这些方法依次注册新的bean定义。
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 触发所有非延迟加载的单例bean的实例化方法
for (String beanName : beanNames) {
// 在前面注解容器中加载的是GenericBeanDefinition,此处转化成了RootBeanDefinition.
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 非抽象类(可实例化)、单例类、非延时加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 是否为工厂方法的方式进行实例化
if (isFactoryBean(beanName)) {
// &+beanName
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
// 此接口是一个专用接口,主要供框架内部和协作框架内部使用。通常,应用程序提供的FactoryBeans应该仅实现简单的FactoryBean接口。
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);
}
}
}
else {
// 关键方法,创建bean
getBean(beanName);
}
}
}
// 忽略以下代码逻辑.
}
- 获取beanNames的列表,这里Spring使用了一个副本作为beanName的数据源.
- 开始触发非延时加载的、单例的bean的实例化方法.
- Spring使用了GenericBeanDefinition作为Bean的属性的载体,在这里会进行merge操作,将具备继承关系的Bean进行递归,最终合并成一个
RootBeanDefinition
.- 检测是否为FactoryBean,如果需要马上进行实例化,那么对其进行
getBean
操作.- 如果不是FactoryBean,也进行
getBean
的操作.- 经过上述的实例化后,提供对
@EventListener
注解的支持.
3. AbstractBeanFactory#getBean
getBean从其字义上来看,是获取Bean对象,但此时容器处于启动刷新阶段,何来的Bean对象呢?我们可以大胆的猜测这其实也是一个创建Bean的入口.如果当前容器不存在此Bean,那么对该Bean进行实例化并进行缓存以备下一次getBean进行使用.
顺藤摸瓜,可以找到在AbstractBeanFactory
中的getBean
方法,发现其内部还调用了doGetBean
这个方法.
/**
* 加载bean,此处调用一个通用的doGetBean方法.
* @param name the name of the bean to retrieve
* @return
* @throws BeansException
*/
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
4. AbstractBeanFactory#doGetBean
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
// 返回Bean名称,必要时去除工厂取消引用前缀,并将别名解析为规范名称
// 通过三种形式获取beanName.
// 1. 原始的beanName.2. FactoryBean->&beanName. 3. alias
String beanName = transformedBeanName(name);
Object bean;
// 尝试从单例缓存集合中获取bean实例
Object sharedInstance = getSingleton(beanName);
// 如果之前已经创建过该单例bean,并且args为空(单例bean不可以用这个args,它是为多例设计的)
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
// 如果Bean还在创建中,则说明是循环依赖.
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,直接返回,如果是factoryBean,则返回它的getObject.
// 主要是处理FactoryBean.
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 如果scope->prototype,singleton.但是在缓存中无法找到
else {
// 如果scope为prototype并且仍然处于创建的状态,那么可以认为是处于循环依赖中了.
// 针对prototype的循环依赖,spring无法解决,此处会抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
BeanFactory parentBeanFactory = getParentBeanFactory();
// 如果在当前容器中无法找到指定名称的bean,此时递归去parentFactory查找.
// 有点类似于类加载的双亲委派机制.
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 针对FactoryBean,将Bean的&重新拼上
String nameToLookup = originalBeanName(name);
// 如果parentBeanFactory属于AbstractBeanFactory实例
if (parentBeanFactory instanceof AbstractBeanFactory) {
// 递归查找
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// 如果有参数,则委派父级容器根据指定名称和显式的参数查找.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// 如果没有参数,委托父级容器根据指定名称和type进行查找
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
// 委派父级容器根据指定名称查找.
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
// 创建的Bean是否需要类型验证
if (!typeCheckOnly) {
// 向容器标记指定的Bean被创建了
markBeanAsCreated(beanName);
}
try {
// 将父类的BeanDefinition与子类的BeanDefinition进行合并覆盖
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 对合并的BeanDefiniton进行检测,主要判断是否为abstract.
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 获取当前Bean所有依赖的Bean名称
String[] dependsOn = mbd.getDependsOn();
// 如果当前Bean设置了dependsOn的属性(用来指定Bean初始化即销毁时的顺序)
// <bean id = A ,Class = "xxx.xxx.A" depends-on = "B">
// <bean id = B ,Class = "xxx.xxx.B">
if (dependsOn != null) {
for (String dep : dependsOn) {
// 检测该依赖是否已经注册给当前Bean
// A-dependsOn-B
// B-dependsOn-A
// 如果是这种情况,直接抛出异常
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 缓存依赖调用,dep->被依赖的beanName
registerDependentBean(dep, beanName);
try {
// 递归调用getBean,注册Bean之间的依赖(C->B->A)
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
// 如果BeanDefiniton为单例
if (mbd.isSingleton()) {
// 匿名内部类,创建Bean实例对象,并且注册给所依赖的对象
// 关键方法:单例类实例化的入口
sharedInstance = getSingleton(beanName, () -> {
try {
// 创建单例bean的入口.
// 如果有父级继承,则对BeanDefinition进行合并
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.
// 显性从单例缓存中删除bean实例.
// 因为单例模式下为了解决循环依赖,可能留有残余的信息,此处进行销毁
destroySingleton(beanName);
throw ex;
}
});
// 获取给定Bean的实例对象
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);
}
// request、session、application
else {
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
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;
}
- 解析BeanName(自动生成beanName、FactoryBean、Alias).
- 尝试从单例缓存集合中获取Bean实例.
- 循环引用检测.
- 如果可以从缓存中获取,直接返回;如果是FactoryBean,调用它的getObject方法.
- 循环引用检测.关于循环依赖这里不细讲,主要梳理主干路线.
- 合并BeanDefinition.
- 检测是否为需要实例化的bean(非抽象、单例),同时检测是否有dependson冲突.
- 如果为需要加载的单例bean.则通过
getSingleton
进行创建.- 如果是原型模式,进行
createBean
.- 对其他scope的处理.
- 检测所需的类型是否与实际bean实例的类型匹配。
4. 1 getSingleton
返回以给定名称注册的(原始)单例对象,如果尚未注册,则创建并注册一个新对象。
传入的是一个lambda表达式产生的函数,其函数式接口为ObjectFactory
.
这里的createBean
其实是实现了其中的getObject
方法.
DefaultSingletonBeanRegistry#getSingleton(String beanName,ObjectFactory<?> singletonFactory)
中会进行getObject的调用.
// Create bean instance.
// 如果BeanDefiniton为单例
if (mbd.isSingleton()) {
// 匿名内部类,创建Bean实例对象,并且注册给所依赖的对象
// 关键方法:单例类实例化的入口
sharedInstance = getSingleton(beanName, () -> {
try {
// 创建单例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.
// 显性从单例缓存中删除bean实例.
// 因为单例模式下为了解决循环依赖,可能留有残余的信息,此处进行销毁
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
5. AbstractAutowireCapableBeanFactory#createBean
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.<br>
* 创建Bean实例,填充Bean实例,应用后处理器等
* @see #doCreateBean
*/
@Override
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.
// 确认当前的Bean类是可以被解析的,并且支持克隆BeanDefinition,merged的BeanDefinition不在此方法的考虑范围
// 进入到里面,会发现器通过了类加载器进行了Class的获取
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// 克隆一份BeanDefinition,用来设置上加载出来的对象
// 采用副本的原因是某些类可能需要动态加载Class
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 检查和准备Bean中的方法覆盖
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 解析BeanPostProcessors的BeanPostProcessorsBeforeInstantiation,试图返回一个需要创建Bean的代理对象
// resolveBeforeInstantiation只针对有自定义的targetsource.
// 因为自定义的targetsource不是Spring的bean,那么后续的初始化与该bean无关
// 因此直接可以进行代理
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的入口
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);
}
}
- 获取需要被解析的Bean的Class.
- 验证MethodOverrides.
- 解析BeanPostProcessorsBeforeInstantiation.检测是否需要返回代理对象.
- doCreateBean->创建bean.
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
// bean实例化包装类
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 从未完成创建的包装bean缓存中清理并获取相关的包装bean实例,单例,不可以重复
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建bean的方式有三种:
// 1.Factory method 2.constructor 3. supplier
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 获取被包装的Bean,后续对bean的改动等于对wrapper进行改动,即对wrapper的改动也会改动bean
Object bean = instanceWrapper.getWrappedInstance();
// 获取实例化对象的类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// 调用BeanDefinition属性合并后完成的BeanPostProcessor->MergedBeanDefinitionPostProcessor
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// @Value、@Autowired的注解解析入口
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 向容器中缓存单例模式的Bean对象,以防止循环引用
// 判断是否要暴露早期引用的bean
// 1. 是否为单例.
// 2. 是否为循环引用
// 3. 是否在创建中的bean
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 匿名内部类,防止循环引用,尽早持有对象的引用
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
// 初始化Bean对象,依赖注入入口
// exposedObject即初始化后返回作为依赖注入完成的bean
Object exposedObject = bean;
try {
// 填充bean实例属性
populateBean(beanName, mbd, instanceWrapper);
// 初始化bean,过程:
// 1. 判断是否实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
// 2. 调用bean初始化的前置操作,即生命周期回调函数.
// @PostConstruct、实现InitializingBean#afterPropertiesSet、具有依赖注入的自定义方法
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
- 初始化BeanWrapper.如果BeanDefinition的scope为singleton,则从缓存中清除.
createBeanInstance
->创建Bean的实例,可以通过三种方式->1.Factory method 2.constructor 3. supplier.
Spring会推断当前用户想通过哪种构造方法进行对象的创建.- 获取到构造方法后,Spring开始进行实例化,这里可以看看Spring是如何对默认的Bean进行实例化的,相信你也有答案,没错,就是反射!
- applyMergedBeanDefinitionPostProcessors,通过后置处理器合并BeanDefiniton对象.
- 向容器缓存单例模式的Bean对象,判断是否需要提前暴露一个bean.
populateBean
->依赖注入触发.- initializeBean,先激活部分Aware接口->BeanNameAware、BeanClassLoaderAware、BeanFactoryAware.
再执行生命周期回调函数.这里不做引申,有兴趣的读者可以查看Spring官网->点我前往- 注册完成依赖注入的bean.
6.1 createBeanInstance过程-推断构造方法.
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 获取Class对象,前面在createBean已经进行过解析了,这里会直接从mbd.getBeanClass()返回
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 检查是否可以破环private的保护进行反射创建实例
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
// 是否通过lambda的方式进行创建.在AbstractBeanDefinition中存储了此值.
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 通过工厂方法创建,factory-method
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
// 空参构造
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 如果已缓存的解析构造函数或者factoryMethod不为空
// 那么可以利用构造函数解析
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
// 自动注入,调用构造函数自动注入
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认的构造函数构造
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// 根据参数解析确定构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 解析的构造器不为空 | 注入类型为AUTOWIRE_CONSTRUCTOR | 有参 | 传入的参数不为空
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 进行对象实例化
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
// 如果没有推断出特殊的构造方法,使用这个默认的模式
// 无参的默认构造方法,内部使用JDK的反射.
return instantiateBean(beanName, mbd);
}
6.2 createBeanInstance过程-分析构造方法策略.
into->instantiateBean
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
// 从这里开始调用反射
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
6.3 createBeanInstance过程-反射获取Constructor
.
into->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;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
// 获取默认的构造方法
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// newInstance
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
6.4 createBeanInstance过程-反射获取实例.
OK,看到newInstance了,此处证明一般的bean都是经过反射进行实例化的
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor);
// 反射
return (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
getBean的学习路线.
- org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
获取Bean实例
- org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton
实例化单例Bean.
- 循环依赖
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean
创建Bean,包括Spring对PostProcessor和Aware接口的支持.
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
Bean的实例化.推断构造函数使用JDK反射创建Java对象...
- BeanWrapper#createBeanInstance
- AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
处理@AutoWired和@Value.
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
注入属性值.
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
生命周期接口回调
- org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessProperties
依赖注入逻辑解析
- org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency
依赖解析
- org.springframework.beans.factory.config.DependencyDescriptor
网友评论