@Resource依赖注入原理

spring可以通过@Resource注解注入依赖,和@Autowired存在区别:

  1. @Autowired默认按类型注入,而@Resource默认按名称和类型结合注入
  2. @Autowired支持通过属性required设置为非必须注入,当依赖不存在时不会报错;@Resource注解不支持
  3. @Autowired能够配合@Qualifier、@Primary、@Priority共同使用

那么spring实现@Resource注解注入依赖的原理是什么,现在可以看下,逻辑不复杂,先判断容器中是否包含需要注入的依赖bean实例对象,没有的话就跟@Autowired解析注入的依赖的方式一样,可以看我前一篇**@Autowired依赖注入原理**,存在的话则到容器中根据name和type获取依赖bean实例对象。

java 复制代码
	protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName)
			throws NoSuchBeanDefinitionException {
......
		if (factory instanceof AutowireCapableBeanFactory) {
			AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;
			DependencyDescriptor descriptor = element.getDependencyDescriptor();
			//容器中没有依赖bean实例对象,则走@Autowired自动注入逻辑
			if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
				autowiredBeanNames = new LinkedHashSet<>();
				resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
				if (resource == null) {
					throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
				}
			}
			//到容器中获取根据name和type获取bean实例对象
			else {
				resource = beanFactory.resolveBeanByName(name, descriptor);
				autowiredBeanNames = Collections.singleton(name);
			}
		}
		else {
			resource = factory.getBean(name, element.lookupType);
			autowiredBeanNames = Collections.singleton(name);
		}
......
		return resource;
	}
	//调用BeanFactory的getBean方法根据name和type获取bean实例对象
	public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
			return getBean(name, descriptor.getDependencyType());
		}
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
		}
	}

获取到依赖bean实例对象后,就会以反射方式set到字段中,进而完成依赖注入。这里可以看出@Resource获取依赖再注入到字段的逻辑相对简单,虽然使用起来没有@Autowired灵活,但是效率会高很多。

java 复制代码
		protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
				throws Throwable {

			if (this.isField) {
				Field field = (Field) this.member;
				ReflectionUtils.makeAccessible(field);
				//反射注入依赖到字段
				field.set(target, getResourceToInject(target, requestingBeanName));
			}
			else {
				if (checkPropertySkipping(pvs)) {
					return;
				}
				try {
					Method method = (Method) this.member;
					ReflectionUtils.makeAccessible(method);
					method.invoke(target, getResourceToInject(target, requestingBeanName));
				}
				catch (InvocationTargetException ex) {
					throw ex.getTargetException();
				}
			}
		}

总结下,spring处理通过@Resource注解注入依赖时,会到容器中根据name和type获取依赖bean实例对象,再反射set注入,更多请关注微信公众号 葡萄开源

相关推荐
初学AI的小高5 小时前
Agent 工具太多怎么办:BM25 检索、依赖补全与按需加载实战
后端·agent
用户6602676118795 小时前
AI 代码上线前的第 24 道门禁:上线失败时,怎样在 10 分钟内退回?
后端·架构
NishikiAsumi07215 小时前
一次170万行的导出:sql优化远没有加索引这么简单
后端
xjz18426 小时前
Rust 注释:从 // 到 rustdoc
后端
syyjhchou7 小时前
自己搭企业内部中转站,怎么让请求更容易命中缓存
人工智能·后端·语言模型·aigc
特立独行的猫A7 小时前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
SomeOtherTime8 小时前
Rust集合(AI回答)
开发语言·后端·rust
我不会起名字3229 小时前
req.Seqs[len-1]:空切片防御缺口与 RPC 二次校验
后端·mongodb·go·即时通讯·im·故障排查
脚本自动化开发9 小时前
京东PLUS开卡红包刷50元的方法
后端
程序员Query9 小时前
day01-认识Go语言 + golang环境的安装
开发语言·后端·golang