spring根据beanName获取bean主要实现:

org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(String, Class<T>, Object[], boolean)

    @SuppressWarnings("unchecked")
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
// 转换对应的beanName
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.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("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);
} // 检查这个工厂中是否存在bean定义
// 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 (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
} if (!typeCheckOnly) {
markBeanAsCreated(beanName);
} // 将存储xml配置文件的GernericBeanDefinition转换为RootBeanDefinition,如果指定的BeanName是子Bean的话同时会合并父类的相关属性
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args); // 保证当前bean所依赖的bean的初始化(递归处理)
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
getBean(dependsOnBean);
registerDependentBean(dependsOnBean, beanName);
}
} // bean的实例化
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
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);
} else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
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);
}
}
}
// 检查需要的类型是否符合bean的实际类型,如果不是进行类型转换
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
// 返回bean
return (T) bean;
}

实际获取过程非常复杂,上面只是显示了获取的主要流程。

参考:spring源码深度解析

spring根据beanName获取bean的更多相关文章

  1. 从Spring容器中获取Bean。ApplicationContextAware

    引言:我们从几个方面有逻辑的讲述如何从Spring容器中获取Bean.(新手勿喷) 1.我们的目的是什么? 2.方法是什么(可变的细节)? 3.方法的原理是什么(不变的本质)? 1.我们的目的是什么? ...

  2. FastJson序列化Json自定义返回字段,普通类从spring容器中获取bean

    前言: 数据库的字段比如:price:1 ,返回需要price:1元. 这时两种途径修改: ① 比如sql中修改或者是在实体类转json前遍历修改. ②返回json,序列化时候修改.用到的是fastj ...

  3. 通过spring工具类获取bean

    package xxx; import org.springframework.beans.BeansException; import org.springframework.beans.facto ...

  4. spring工具类获取bean

    import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebAppl ...

  5. Spring - 运行时获取bean(ApplicationContextAware接口)

    默认情况下,我们的bean都是单例模式(即从容器初始化到销毁只保持一个实例).当一个bean需要引用另外一个bean,我们往往会通过bean属性的方式通过依赖注入来引用另外一个bean.那么问题就来了 ...

  6. Spring容器中获取bean实例的方法

    // 得到上下文环境 WebApplicationContext webContext = ContextLoader .getCurrentWebApplicationContext(); // 使 ...

  7. Tomcat启动后,从spring容器中获取Bean和ServletContext

    public static Object getBean(String beanName){ ApplicationContext context = ContextLoader.getCurrent ...

  8. 使用Spring容器动态注册和获取Bean

    有时候需要在运行时动态注册Bean到Spring容器,并根据名称获取注册的Bean.比如我们自己的SAAS架构的系统需要调用ThingsBoard API和Thingsboard交互,就可以通过Thi ...

  9. 【Spring】初始化Spring IoC容器(非Web应用),并获取Bean

    参考文章 Introduction to the Spring IoC container and beans BeanFactory 和ApplicationContext(Bean工厂和应用上下文 ...

随机推荐

  1. [TCP/IP] TCP的报文头

    1.源端口和目的端口:各占2个字节,分别写入源端口和目的端口: 2.序列号:占4个字节,TCP连接中传送的字节流中的每个字节都按顺序编号.例如,一段报文的序号字段值是 301 ,而携带的数据共有100 ...

  2. 构建Apache Web服务器

    Apache 是世界使用排名第一的 Web 服务器软件.它可以运行在几乎所有广泛使用的计算机平台上,由于其跨平台和安全性被广泛使用,是最流行的 Web 服务器端软件之一.Apache工作模式有多种,其 ...

  3. PAC在异常检测中的应用

    注:资料均来源于网络,本文只做知识分享,如侵立删,谢谢. PAC算法背景简述: 在许多领域的研究与应用中,通常需要对含有多个变量的数据进行观测,收集大量数据后进行分析寻找规律.多变量大数据集无疑会为研 ...

  4. 青春正盛,未来可期。马上2020了,低成本投资自己:vip测试提升圈

    应部分群友再三强烈建议要求,组建了一个测试提升小分队,相约vip测试提升圈, 这里汇集了一群热爱学习.渴望提升的测试小伙伴,大家都朝着自己的梦想拼命努力: 此圈将助你在接口自动化和性能方向全面提升,提 ...

  5. 02-cmake语法-if、条件表达

    格式: if(expression) # then section. COMMAND1(ARGS ...) COMMAND2(ARGS ...) ... elseif(expression2) # e ...

  6. <String> 345 205

    345. Reverse Vowels of a String 头尾指针开始扫描. String.contains(char) class Solution { public String rever ...

  7. Maven使用第三方Jar文件

    本例中,需要在Maven项目里添加uiautomator.jar文件.以下介绍两种方法: 方法一:在pom.xml里指定jar文件目录 <dependency> <groupId&g ...

  8. 教你查阅Java API 英文文档(JDK 11)

    JAVA Document:https://docs.oracle.com/en/java/javase/11/ 然后找到“Specifications”并点击 API Documentation 比 ...

  9. Windwos Server 2016 远程桌面授权

    https://blog.csdn.net/hanzheng260561728/article/details/80443135 第二步激活客户的的时候,注意事项

  10. wifi串口服务器

    下面与大家分享上海卓岚无线wifi串口服务器ZLAN7104创建虚拟串口的设置使用心得 一.7104网线连接计算机,用ZLVircom即可搜索并配置 其中,串口设置需要匹配实际所接的串口设备,配置为相 ...