AbstractBeanFactory类里面getBean 里面涉及的流程和分支情况都比较多,下面是 大致的流程图:
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
//取指定 alias 所表示的最终 beanName,例如别名 A 指向名称为 B 的 bean 则返回 B;
//若别名 A 指向别名B,别名B又指向名称为 C 的 bean 则返回 C。
//如果是以&开头,那么就是FactoryBean,去掉开头的&符号
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
// 这里先从缓存中获取或者从singletonFactories中的objectFactory中获取
//为什么会首先使用这段代码呢?
//因为在创建单例Bean的时候,会存在依赖注入的情况,而在创建依赖的时候,为了避免循环依赖,
//Spring 创建bean 的原则是不等Bean 创建完成就会将创建Bean的ObjectFactory 提前曝光,也就是先将ObjectFactory 加入到缓存中,一旦下个Bean 创建时依赖上个bean ,则直接使用ObjectFactory
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
// 日志打印,提示此Bean 还没有完全初始化,在一个循环引用中
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);
}
else {
// 如果是原型模型,存在循环依赖,那就直接报错,原型模型是不允许循环依赖的
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
//如果父类工厂不为空,并且当前beanDefinitionMap 没有对应的beanName ,那就委托父类处理,
//以父工厂为准
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
// 获取最终name
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);
}
}
//如果不是仅仅做类型检查则是创建bean,这里进行记录,加入到alreadyCreated 里面,表示已经创建
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
// 进行BeanDefinition 的转换为RootBeanDefinition ,如果存在父类,就和父类的属性
//进行合并
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 判断mbd 是否是 abstract的,如果是就报错
// 意味着不要实例化它本身,而仅用作具体子bean定义的父对象。
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//判断是否有依赖的Bean ,如果有,先对依赖的Bean 进行创建
//代码里面有时想提前初始化的,都是加上@DependsOn
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
// 判断是否循环依赖的情况,就是A Bean里面指定先要初始化B ,B里面指定先要初始化A这种情况
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 进行登记缓存对应的依赖关系
registerDependentBean(dep, beanName);
try {
// 先创建对应的依赖的Bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
// 创建单例模式
if (mbd.isSingleton()) {
//进行单例模式的创建
sharedInstance = getSingleton(beanName, () -> {
try {
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;
}
});
// 获取对应的实例
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
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;
}
getBean 的流程步骤主要如下:
1. 转换对应 beanName
或许很多人不理解转换对应 beanNarne 是什么意思,传人的参数 name 不就是 beanNarne 吗?其实不是,这里传入的参数可能是别名,也可能是 FactoryBean,所以需要进行一系列的解析,这些解析内容包括如下内容。
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
在这块代码里面,有好几个类似的Map ,先解释一下各自的作用:
public Object getSingleton(String beanName) {
// 参数true 设置 运行提前进行依赖
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从singletonObjects 获取对应的Bean 实例
Object singletonObject = this.singletonObjects.get(beanName);
// 如果未获取到,并且在创建过程中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//从earlySingletonObjects 中获取对应的Bean 实例
singletonObject = this.earlySingletonObjects.get(beanName);
// 未获取到,并且允许提前依赖
if (singletonObject == null && allowEarlyReference) {
//获取对应的ObjectFactory,调用其getOjbect() 方法进行Bean的创建
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
//将创建的Bean 实例 放入到 earlySingletonObjects 里面
this.earlySingletonObjects.put(beanName, singletonObject);
// 将beanName 从singletonFactories 里面移除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
这里的主要流程分析如下:
这里涉及到ObjectFactory相关的,详细可以查看 这块Spring源码解析之-ObjectFactory、BeanFactory、FactoryBean分析
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// 如果 name 是以&开头,说明是要获取FactoryBean本身实例,而不是通过getObject() 创建的实例
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
// 如果不是FactoryBean 类型,抛出异常
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
}
// 如果不是 FactoryBean类型,或者name 是以& 开头,那就直接返回
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
//从 缓存factoryBeanObjectCache 里面获取
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
//转成FactoryBean 类型
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// 如果是单例模式,已经加载之后会存放在beanDefinitionMap 里面
// 这里检查是否已经存在beanName 对应的对象
if (mbd == null && containsBeanDefinition(beanName)) {
//合并父类相关的属性,转换成RootBeanDefinition
mbd = getMergedLocalBeanDefinition(beanName);
}
// 判断此RootBeanDefinition 是否是合成的(被动态代理过)
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
// 如果是单例模式 并且factoryBean 本身的实例已经创建
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
// 再次从缓存中获取,如果存在就直接返回
Object object = this.factoryBeanObjectCache.get(beanName);
// 如果不存在,调用doGetObjectFromFactoryBean 这里是关键,其实里面就是 调用
//object = factory.getObject(); 这里是核心
if (object == null) {
object = doGetObjectFromFactoryBean(factory, beanName);
// 这里再次check
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
// 判断是否需要后置处理
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// 还在创建中,直接返回
return object;
}
//check ,并加入到singletonsCurrentlyInCreation 里面
beforeSingletonCreation(beanName);
try {
// 进行后置处理
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
// check,并从 singletonsCurrentlyInCreation 里面移除
afterSingletonCreation(beanName);
}
}
// 如果 单例缓存 singletonObjects里面有FactoryBean 对应的实例,那么就 把Object 放到
//缓存factoryBeanObjectCache 里面
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
// 如果不是单例模式,是原型模式,直接 通过doGetObjectFromFactoryBean 的getObject 创建
// 并且也没有必要放入缓存
Object object = doGetObjectFromFactoryBean(factory, beanName);
// 是否需要后置处理
if (shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
throws BeanCreationException {
Object object;
try {
// 权限验证
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 这里就是关键,调用 FactoryBean 的getObject() 方法创建对象
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
//如果为null,创建一个NullBean 对象
object = new NullBean();
}
return object;
}
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
// 判断缓存mergedBeanDefinitions 是否包含beanName 对应的 数据
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null) {
return mbd;
}
// 先从beanDefinitionMap 获取数据,并开始进行 merge
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
// 这里的 containingBd 传入的为 null,就是没有对应的 外部bean
return getMergedBeanDefinition(beanName, bd, null);
}
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
// 从 mergedBeanDefinitions 尝试获取
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
// 如果 parentName 为null,就直接进行转换为RootBeanDefinition 类型
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
// 先对parentName 进行转换,获取最终的parentBeanName
String parentBeanName = transformedBeanName(bd.getParentName());
// 如果beanName 和parentBeanName 不相等 ,就先获取对应的父类定义的BeanDefinition
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
// 如果相等,先获取父容器,并判断父容器是否是 ConfigurableBeanFactory 类型
// 再获取对应的父类定义的BeanDefinition
BeanFactory parent = getParentBeanFactory();
if (parent instanceof ConfigurableBeanFactory) {
//获取对应的父类定义的BeanDefinition
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
// 将父类定义的BeanDefinition 转换为 RootBeanDefinition
mbd = new RootBeanDefinition(pbd);
进行 子类和父类的属性覆盖
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
// 如果没有配置,默认是单例模式
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
//一个bean 包含在一个非单例模式的bean里面,此bean 本身不能为单例模式
//这种情况在之前步骤,进行父-子bean合并时,子bean 对父bean 进行了覆盖,
//应该是继承父属性的非单例模式
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
// 如果containingBd 为null,并且需要缓存,就放入到mergedBeanDefinitions 里面
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
return mbd;
}
}
protected boolean isDependent(String beanName, String dependentBeanName) {
// 先锁住
synchronized (this.dependentBeanMap) {
return isDependent(beanName, dependentBeanName, null);
}
}
private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
// 如果alreadySeen 不为空,并且已经包含了 beanName 就返回false
if (alreadySeen != null && alreadySeen.contains(beanName)) {
return false;
}
// 将beanName 转为最终的name
String canonicalName = canonicalName(beanName);
// 从dependentBeanMap 获取对应的已经存在的依赖关系
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
// 如果为null,直接返回
if (dependentBeans == null) {
return false;
}
// 如果包含,返回true
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
for (String transitiveDependency : dependentBeans) {
if (alreadySeen == null) {
alreadySeen = new HashSet<>();
}
alreadySeen.add(beanName);
// 迭代循环进行判断
if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
return true;
}
}
return false;
}
// 这里是进行加入缓存,以便下次使用
public void registerDependentBean(String beanName, String dependentBeanName) {
String canonicalName = canonicalName(beanName);
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 从缓存singletonObjects里面获取
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 如果此bean 正在销毁,就抛出异常
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 + "'");
}
// 这里做一个check 操作,并加入到singletonsCurrentlyInCreation 里面
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 这里就是核心,通过调用 ObjectFactory.getObject() 进行创建,这里就是传入得createBean方法
//createBean 见下面得详细分析
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;
}
// 创建完了做一个check操作,并从singletonsCurrentlyInCreation 里面移除
afterSingletonCreation(beanName);
}
if (newSingleton) {
对缓存进行更新
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 对缓存进行更新,加入到singletonObjects 、registeredSingletons里面
//从singletonFactories、earlySingletonObjects移除
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
从源码可以看出,大致流程如下:
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 已经解析好了,就是用classLoader 或者 class.forName 对定义的类名进行加载,
//并把解析好的类保存带BeanDefinition 里面,以供后面使用里面还对 SPEL语言支持
//这个方法主要是解析 bean definition 的 class 类,并将已经解析的 Class 存储在 bean definition 中以供后面使用。
//这样做的主要目的是动态解析的 class 是无法保存到共享的 BeanDefinition 中。
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
// 验证以及准备覆盖的方法
try {
// 验证并准备为此bean定义的方法覆盖。检查是否存在具有指定名称的方法。
//这里 主要是处理配置了lookup-method,replace-method两种依赖注入的方式,
// 下面有详细的方法解释
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.
//给 BeanPostProcessors 一个机会来返回代用来代替真正的实例
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 {
// 进行创建
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);
}
}
protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
// 如果已经有对应的BeanClass ,说明已经解析好了,那就直接返回
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
// 这里判断是否有权限设置,然后调用doResolveBeanClass 方法
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>) () ->
doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
}
else {
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
throws ClassNotFoundException {
// 这里首先获取 对应的ClassLoader ,从 当前的Thread级别->class级别->system级别 获取
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;
boolean freshResolve = false;
// 如果对应的typesToMatch 不为空
if (!ObjectUtils.isEmpty(typesToMatch)) {
// When just doing type checks (i.e. not creating an actual instance yet),
// use the specified temporary class loader (e.g. in a weaving scenario).
// 做类型检查时,使用指定的临时加载器
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
// 这里将dynamicLoader 指向指定的临时加载器,并将标识 置位true ,用于下面进行类加载
dynamicLoader = tempClassLoader;
freshResolve = true;
if (tempClassLoader instanceof DecoratingClassLoader) {
DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
for (Class<?> typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
}
}
// 获取对的的 full className
String className = mbd.getBeanClassName();
if (className != null) {
// 这里主要是增加SPEL语言支持,SpEL使用#{...}作为定界符
//比如 #{db.user} 这类
Object evaluated = evaluateBeanDefinitionString(className, mbd);
// 如果className 和 evaluated 不相等,那就是需要进一步的处理
if (!className.equals(evaluated)) {
// A dynamically resolved expression, supported as of 4.2...
// 如果evaluated已经是Class 类型,直接返回
if (evaluated instanceof Class) {
return (Class<?>) evaluated;
}
// 如果不是,那就先将 className 赋值evaluated ,并将 标识置位true,后面需要进行 类加载
else if (evaluated instanceof String) {
className = (String) evaluated;
freshResolve = true;
}
else {
throw new IllegalStateException("Invalid class name expression result: " + evaluated);
}
}
// 如果标识为true ,需要进行类加载
if (freshResolve) {
// When resolving against a temporary class loader, exit early in order
// to avoid storing the resolved Class in the bean definition.
// 这里使用classLoader 或者ClassUtils.forName 进行类加载
if (dynamicLoader != null) {
try {
return dynamicLoader.loadClass(className);
}
catch (ClassNotFoundException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
}
}
}
return ClassUtils.forName(className, dynamicLoader);
}
}
// Resolve regularly, caching the result in the BeanDefinition...
// 进行解析,并把解析结果 缓存到beanClass对象里面
return mbd.resolveBeanClass(beanClassLoader);
}
// 这里主要是增加SPEL语言支持,SpEL使用#{...}作为定界符
protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
// 如果bean 表达式解析器为 null ,直接返回对应的Bean class name
if (this.beanExpressionResolver == null) {
return value;
}
Scope scope = null;
if (beanDefinition != null) {
String scopeName = beanDefinition.getScope();
if (scopeName != null) {
// 获取对应的模式
scope = getRegisteredScope(scopeName);
}
}
// 这里是进行解析,主要是针对SPEL语言 的解析,#{...} ,以#{开头,以 }结尾
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
// 验证是否有 lookup-methods 方法存在的,如果有,进行统计对应的方法个数
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
// Check that lookup methods exists.
if (hasMethodOverrides()) {
Set<MethodOverride> overrides = getMethodOverrides().getOverrides();
synchronized (overrides) {
for (MethodOverride mo : overrides) {
prepareMethodOverride(mo);
}
}
}
}
// 统计个数,如果 为0 个,就报错,说明配置错误
// 如果为1个,设置setOverloaded 为false,在方法调用的时候就不需要根据参数类型来判断到底重载的是哪个方法
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
if (count == 0) {
throw new BeanDefinitionValidationException(
"Invalid method override: no method with name '" + mo.getMethodName() +
"' on class [" + getBeanClassName() + "]");
}
else if (count == 1) {
// Mark override as not overloaded, to avoid the overhead of arg type checking.
//标记 MethodOveride未被被盖, 避免参数类型检查的开销。
mo.setOverloaded(false);
}
}
下面来自《Spring 源码深度解析》的解释:
之前反复提到过,在 Spring 配置中存在lookup-method 和 replace-method 两个配置功能,而这两个配置的加载其实就是将配置 统一存放在 BeanDefinition 中的 methodOverrides 属性里,这两个功能实现原理其实是在 bean 实例化的时候如果检测到存在 methodOverrides 属性,会动态地为当前 bean 生成代理并使用对应 的拦截器为 bean 做增强处理,相关逻辑实现在 bean 的实例化部分详细介绍。 但是这里要提到的是,对于方法的匹配来讲,如果一个类中存在若干个重载方法,那么, 在函数调用及增强的时候还需要根据参数类型进行匹配,来最终确认当前调用的到底是哪个函 数。 但是, Spring 将一部分匹配工作在这里完成了,如果当前类中的方法只有一个,那么就设 置重载该方法没有被重载,这样在后续调用的时候便可以直接使用找到的方法,而不需要进行 方法的参数匹配验证了,而且还可以提前对方法存在性进行验证,正可谓一箭双雕。
详见Spring源码解析之-doCreateBean() 详解