spring根据beanName获取bean
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的更多相关文章
- 从Spring容器中获取Bean。ApplicationContextAware
引言:我们从几个方面有逻辑的讲述如何从Spring容器中获取Bean.(新手勿喷) 1.我们的目的是什么? 2.方法是什么(可变的细节)? 3.方法的原理是什么(不变的本质)? 1.我们的目的是什么? ...
- FastJson序列化Json自定义返回字段,普通类从spring容器中获取bean
前言: 数据库的字段比如:price:1 ,返回需要price:1元. 这时两种途径修改: ① 比如sql中修改或者是在实体类转json前遍历修改. ②返回json,序列化时候修改.用到的是fastj ...
- 通过spring工具类获取bean
package xxx; import org.springframework.beans.BeansException; import org.springframework.beans.facto ...
- spring工具类获取bean
import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebAppl ...
- Spring - 运行时获取bean(ApplicationContextAware接口)
默认情况下,我们的bean都是单例模式(即从容器初始化到销毁只保持一个实例).当一个bean需要引用另外一个bean,我们往往会通过bean属性的方式通过依赖注入来引用另外一个bean.那么问题就来了 ...
- Spring容器中获取bean实例的方法
// 得到上下文环境 WebApplicationContext webContext = ContextLoader .getCurrentWebApplicationContext(); // 使 ...
- Tomcat启动后,从spring容器中获取Bean和ServletContext
public static Object getBean(String beanName){ ApplicationContext context = ContextLoader.getCurrent ...
- 使用Spring容器动态注册和获取Bean
有时候需要在运行时动态注册Bean到Spring容器,并根据名称获取注册的Bean.比如我们自己的SAAS架构的系统需要调用ThingsBoard API和Thingsboard交互,就可以通过Thi ...
- 【Spring】初始化Spring IoC容器(非Web应用),并获取Bean
参考文章 Introduction to the Spring IoC container and beans BeanFactory 和ApplicationContext(Bean工厂和应用上下文 ...
随机推荐
- [TCP/IP] 关闭连接后为什么客户端最后还要等待2MSL
MSL(Maximum Segment Lifetime)报文最大生存时间,2MSL即两倍的MSL,TCP允许不同的实现可以设置不同的MSL值. 第一,保证客户端发送的最后一个ACK报文能够到达服务器 ...
- C语言结构体(摘抄C语言设计)
struct Student stu_1;//定义struct Student 类型的变量stu_1 struct Student *p;//定义指向struct Student类型数据的指针变量 p ...
- glog的编译和使用
glog是google提供的一个轻量级日志库,有chromium开发经验的人都会发现,它和base库中的日志库非常像,其实base库中的日志库比它更加轻量级.glog在日常开发中的使用非常广泛.这里介 ...
- jenkins slave上执行脚本报错
jenkins slave上执行脚本报错 解决方法:在系统配置中设置shell execuate C:\Windows\system32\cmd.exe 保存即可
- python 面试真题
0.Python是什么? Python是一种解释型语言.但是跟C和C的衍生语言不同,Python代码在运行之前不需要编译.其他解释型语言还包括PHP和Ruby. Python是动态类型语言,指的是在声 ...
- nwjs-简介
nwjs是基于nodejs的,它支持nodejs所有的api,主要用于跨平台轻量级桌面应用开发,运行环境包括32位和64位的Window.Linux和Mac OS nwjs是在英特尔开源技术中心创建的 ...
- n8n 试用
前边有简单的介绍n8n,如果大家看了官方网站会有一个比较醒目的说明zapier以及tray.io的开源替代方案 以下是一个简单的试用 环境准备 docker-compose 文件 version: ...
- scrapy机制mark(基于twisted)
twisted twisted管理了所有的异步任务 Twisted的主线程是单线程的,即reactor线程: 而这些io耗时操作会在线程池中运行,不再twisted主线程中运行,即通过线程池来执行异步 ...
- 调试经验分享-让自己的电脑充当WI-Fi模块,用来抓取连接Wi-Fi模块APP上的通信数据
需求 手头有了厂家的APP和Wi-Fi模块 在已经知道APP是通过TCP连接Wi-Fi模块(8266), 同时也知道了连接的端口号的 情况下如何知道厂家的APP发送给Wi-Fi模块的数据 打开自己的笔 ...
- luoguP4551最长异或路径
P4551最长异或路径 链接 luogu 思路 从\(1\)开始\(dfs\)求出\(xor\)路径.然后根据性质\(x\)到\(y\)的\(xor\)路径就是\(xo[x]^xo[y]\) 代码 # ...