@Autowired 和 @Resource区别,简单测试容器中多个相同bean的情况

@Autowired 和 @Resource 区别

  • @Autowired 来自Spring, @Resource 来自java;
  • @Autowired 默认按类型注入,容器中存在多个相同类型的 Bean,将抛出异常。 可以配合使用 @Qualifier 指定名称。

两个相同类型(都 implements Formatter)的 Bean:

@Component("fooFormatter")
public class FooFormatter implements Formatter {public String format() {return "foo";}
}
@Component("barFormatter")
public class BarFormatter implements Formatter {public String format() {return "bar";}
}

直接使用 @Autowired:
容器启动失败: Field formatter in com.example.SpringInitialzrDemo.autowired.FooService required a single bean, but 2 were found

public class FooService {@Autowiredprivate Formatter formatter; // 容器启动失败: Field formatter in com.example.SpringInitialzrDemo.autowired.FooService required a single bean, but 2 were found
}

使用 @Autowired + @Qualifie:
容器启动成功

    @Autowired@Qualifier("barFormatter")private Formatter formatter;
  • @Resource 可以根据名称,可以根据类型。
    针对上面两个相同类型的 Bean,就可以使用
 	@Resource(name = "barFormatter") private Formatter formatter;

或:

 	@Resource(type = FooFormatter.class)private Formatter formatter;

@Autowired 和 @Resource 的参数

  • @Autowired 只有一个参数 required

@Autowired 里的参数 required = true (默认) 的用途:
启动容器时会校验这个Bean在容器中是否存在,不存在会阻止项目启动,并报错:

FooService required a bean of type 'xxx' that could not be found

如果使用 @Autowired(required = false) ,则不影响项目的启动。 当然,后续使用到还是会空指针。

  • @Resource 参数有多个,主要就使用name 和 type,分别指定名称和类型。

向容器注入多个相同名称的bean

使用@Component的方式:
public interface BeanService {
}
@Component("beanService")
public class OneServiceImpl implements BeanService{
}
@Component("beanService")
public class TwoServiceImpl implements BeanService{
}

启动时报错: BeanDefinitionStoreException:

Annotation-specified bean name 'beanService' for bean class [com.example.bean.TwoServiceImpl] conflicts with existing, non-compatible bean definition of same name and class [com.example.bean.OneServiceImpl]

上诉bean有相同name且有相同类型(都是BeanService类型), 如果时不相同的类型呢:

@Component("beanService")
public class OneServiceImpl {
}
@Component("beanService")
public class TwoServiceImpl {
}

启动时还是报错:BeanDefinitionStoreException。

总结:使用@Component就是不能注入同名bean的,会在容器启动时就报错,且不受类型影响。
使用 @Bean方式

取消@Component注解,并使用一个Appfig类来注入:

@Configuration
public class AppConfig {@Bean("beanService")public BeanService oneServiceImpl() {return new OneServiceImpl();}@Bean("beanService")public BeanService twoServiceImpl() {return new TwoServiceImpl();}@Bean("beanService")public BeanService threeServiceImpl() {return new ThreeServiceImpl();}
}

@Bean注入三个bean,且名称都叫beanService。

启动容器没有报错。

  • 在测试类中,使用 @Autowired注入BeanService
    @Autowiredprivate BeanService beanService;

并输出bean实际类型:

    Class<? extends BeanService> aClass = beanService.getClass();System.out.println(aClass.getName());  // com.example.SpringInitialzrDemo.bean.OneServiceImpl

输出了OneServiceImpl,那么容器中到底有几个bean呢?

使用 applicationContext.getBeanDefinitionNames() 查看,只有一个 “beanService”。

  • 在测试类中,使用 @Resource注入BeanService,并强制指定类型为 TwoServiceImpl.class
    @Resource(type = TwoServiceImpl.class)private BeanService beanService;

结果报错:

BeanNotOfRequiredTypeException: Bean named 'beanService' is expected to be of type 'com.example.SpringInitialzrDemo.bean.TwoServiceImpl' but was actually of type 'com.example.SpringInitialzrDemo.bean.OneServiceImpl'

容器里是没有TwoServiceImpl, 是因为没有注入,还是被覆盖了?

继续测试,增加输出:

@Configuration
public class AppConfig {@Bean("beanService")public BeanService oneServiceImpl() {System.out.println("我要注入:OneServiceImpl");return new OneServiceImpl();}@Bean("beanService")public BeanService twoServiceImpl() {System.out.println("我要注入:TwoServiceImpl");return new TwoServiceImpl();}@Bean("beanService")public BeanService threeServiceImpl() {System.out.println("我要注入:ThreeServiceImpl");return new ThreeServiceImpl();}
}

结果:只输出了 “我要注入:OneServiceImpl”。

总结:使用 @Configuration + @Bean 的方式,注入多个同名bean,容器正常启动,但实际只有第一个被成功注入。

即便使用 @Primary 指定第二个优先。实际上还是注入的OneServiceImpl。(说明@Primary不是这么用的)

    @Bean("beanService")@Primarypublic BeanService twoServiceImpl() {System.out.println("我要注入:TwoServiceImpl");return new TwoServiceImpl();}

@Import的方式就暂不做测试了

上述例子是以注入多个相同名称不同类型的bean,接下来 测试注入多个相同类型的bean。

向容器注入多个相同类型的bean

@Configuration
public class AppConfig {@Beanpublic BeanService oneServiceImpl() {System.out.println("我要注入:OneServiceImpl");return new BeanService();}@Beanpublic BeanService twoServiceImpl() {System.out.println("我要注入:TwoServiceImpl");return new BeanService();}@Beanpublic BeanService threeServiceImpl() {System.out.println("我要注入:ThreeServiceImpl");return new BeanService();}
}
  • 使用@Autowired
    @Autowiredprivate BeanService beanService;

容器无法启动:

Field beanService in ___ required a single bean, but 3 were found
  • 使用 @Resource
    @Resourceprivate BeanService beanService;

容器无法启动:

BeanCreationException:No qualifying bean of type 'com.example.SpringInitialzrDemo.bean2.BeanService' available: expected single matching bean but found 3
  • 使用 @Autowired + @Qualifier 并指定bean名称
    @Autowired@Qualifier("oneServiceImpl")private BeanService beanService;

容器可以正常启动。

  • 使用 @Resource(name = “twoServiceImpl”)
    @Resource(name = "twoServiceImpl")private BeanService beanService;

容器可以正常启动。

  • 使用@Primary
@Configuration
public class AppConfig {@Beanpublic BeanService oneServiceImpl() {System.out.println("我要注入:OneServiceImpl");return new BeanService();}@Bean@Primarypublic BeanService twoServiceImpl() {System.out.println("我要注入:TwoServiceImpl");return new BeanService();}@Beanpublic BeanService threeServiceImpl() {System.out.println("我要注入:ThreeServiceImpl");return new BeanService();}
}

这样,使用 @Autowired 或@Resource 时不指定名称,就会默认使用@Primary的这个bean,容器也可以正常启动。

    @Resourceprivate BeanService beanService;
总结:使用 @Configuration + @Bean 相同类型但是不同名称bean时,这些同类型的bean都能被创建,但必须在注入时指定bean名称,或使用@Primary标识其中一个bean的优先级。

验证,输出所有的bean:

	ConfigurableApplicationContext applicationContext = SpringApplication.run(SpringInitialzrDemoApplication.class, args);String[] names = applicationContext.getBeanDefinitionNames();for (String name : names) {System.out.println(">>>>>>" + name);}

结果:会找到三个bean确实都是成功创建.

>>>>>>oneServiceImpl
>>>>>>twoServiceImpl
>>>>>>threeServiceImpl

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/25504.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

国产操作系统上给virtualbox中win7虚拟机安装增强工具 _ 统信 _ 麒麟 _ 中科方德

原文链接&#xff1a;国产操作系统上给virtualbox中win7虚拟机安装增强工具 | 统信 | 麒麟 | 中科方德 Hello&#xff0c;大家好啊&#xff01;今天给大家带来一篇在国产操作系统上给win7虚拟机安装virtualbox增强工具的文章。VirtualBox增强工具&#xff08;Guest Additions&a…

Liunx环境下redis主从集群搭建(保姆级教学)02

Redis在linux下的主从集群配置 本次演示使用三个节点实例一个主节点&#xff0c;两个从节点&#xff1a;7000端口&#xff08;主&#xff09;&#xff0c;7001端口&#xff08;从&#xff09;&#xff0c;7002端口&#xff08;从&#xff09;&#xff1b; 主节点负责写数据&a…

Rust-02-变量与可变性

在Rust中&#xff0c;变量和可变性是两个重要的概念。 变量&#xff1a;变量是用于存储数据的标识符。在Rust中&#xff0c;变量需要声明其类型&#xff0c;例如&#xff1a; let x: i32 5; // 声明一个名为x的变量&#xff0c;类型为i32&#xff08;整数&#xff09;&#…

mybatis增加日志打印插件

可以在分页插件PageHelperAutoConfiguration注入的时候&#xff0c;注入日志打印插件 public void afterPropertiesSet() {PageInterceptor interceptor new PageInterceptor(this.helperProperties);interceptor.setProperties(this.helperProperties.getProperties());for …

安装MySQL Sample Database

本文安装的示例数据库为官方的Employees Sample Database。 操作过程参考其安装部分。 在安装前&#xff0c;MySQL已安装完成&#xff0c;环境为Linux。 克隆github项目&#xff1a; $ git clone https://github.com/datacharmer/test_db.git Cloning into test_db... remo…

华为和锐捷设备流统配置

华为&#xff1a; <AR6121E-S>dis acl 3333 Advanced ACL 3333, 4 rules Acls step is 5 rule 5 permit icmp source 192.168.188.2 0 destination 192.168.88.88 0 rule 10 permit icmp source 192.168.88.88 0 destination 192.168.188.2 0 rule 15 permit udp so…

【西瓜书】6.支持向量机

目录&#xff1a; 1.分类问题SVM 1.1.线性可分 1.2.非线性可分——核函数 2.回归问题SVR 3.软间隔——松弛变量 3.1.分类问题&#xff1a;0/1损失函数、hinge损失、指数损失、对率损失 3.2.回归问题&#xff1a;不敏感损失函数、平方 4.正则化

计算机组成原理之指令格式

1、指令的定义 零地址指令&#xff1a; 1、不需要操作数&#xff0c;如空操作、停机、关中断等指令。 2、堆栈计算机&#xff0c;两个操作数隐藏在栈顶和此栈顶&#xff0c;取两个操作数&#xff0c;并运算的结果后重新压回栈顶。 一地址指令&#xff1a; 二、三地址指令 四…

配置免密登录秘钥报错

移除秘钥&#xff0c;执行 ssh-keygen -R cdh2即可 参考&#xff1a;ECDSA主机密钥已更改,您已请求严格检查。 - 简书

nocas配置加载失败解决-笔记

nacos配置加载失败问题-笔记 背景解决过程解决方案 各位遇到的问题不尽相同&#xff0c;本文只记录 自己 遇到的问题并及如何解决 背景 最近接手的一个微服务架构项目&#xff0c;同事搭建的框架&#xff0c;按照配置一步一步搬运到nacos上&#xff0c;本地启动测试通过&…

记录一个Qt调用插件的问题

问题背景 使用Qt主程序插件的方式开发&#xff0c;即主程序做成一个框&#xff0c;定义好插件接口&#xff0c;然后主程序上通过插件接口与插件进行交互。调试过程中遇到了两个问题&#xff0c;在这里记录一下。 问题1&#xff08;信号槽定义&#xff09; 插件与主程序之间&am…

python 做成Excel并设置打印区域

记录首次用python处理Excel表格的过程。 参考文章&#xff1a;https://www.jianshu.com/p/5e00dc2c9f4c 程序要做的事情&#xff1a; 1. copy 模板文件到 output 文件夹并重命名为客户指定的文件名 2. 从 DB 查询数据并将数据写入 Excel 3. 写数据的同时&#xff0c; 设置每…

Python爬虫入门与登录验证自动化思路

1、pytyon爬虫 1.1、爬虫简介 Python爬虫是使用Python编写的程序&#xff0c;可以自动访问网页并提取其中的信息。爬虫可以模拟浏览器的行为&#xff0c;自动点击链接、填写表单、进行登录等操作&#xff0c;从而获取网页中的数据。 使用Python编写爬虫的好处是&#xff0c;…

【数据结构】十二、八种常用的排序算法讲解及代码分享

目录 一、插入排序 1)算法思想 2&#xff09;代码 二、希尔排序 1&#xff09;算法思想 2&#xff09;代码 三、选择排序 1&#xff09;算法思想 2&#xff09;代码 四、堆排序 1&#xff09;什么是最大堆 2&#xff09;如何创建最大堆 3&#xff09;算法思想 4&a…

C# Excel操作类EPPlus

摘要 EPPlus 是一个流行的用于操作 Excel 文件的开源库&#xff0c;适用于 C# 和 .NET 环境。它提供了丰富的功能&#xff0c;能够轻松地读取、写入和格式化 Excel 文件&#xff0c;使得在 C# 中进行 Excel 文件处理变得更加简单和高效。EPPlus 不需要安装 Microsoft Office 或…

ai写作文

天津市高考作文题 阅读下面的材料&#xff0c;根据要求写作。 在缤纷的世界中&#xff0c;无论是个人、群体还是国家&#xff0c;都会面对别人对我们的定义。我们要认真对待“被定义”&#xff0c;明辨是非&#xff0c;去芜存真&#xff0c;为自己的提升助力&#xff1b;也要勇…

知乎网站只让知乎用户看文章,普通人看不了

知乎默认不显示全部文章&#xff0c;需要点击展开阅读全文 然而点击后却要登录&#xff0c;这意味着普通人看不了博主写的文章&#xff0c;只有成为知乎用户才有权力查看文章。我想这不是知乎创作者希望的情况&#xff0c;他们写文章肯定是希望所有人都能看到。 这个网站篡改…

应用商店如何检测在架应用内容是否违规?

&#x1f3c6;本文收录于「Bug调优」专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收藏&&…

线性代数|机器学习-P11方程Ax=b求解研究

文章目录 1. 变量数和约束条件数大小分类2. 最小二乘法和Gram-schmidt变换2.1 Gram-schmidt变换2.2 最小二乘法2.2.1 损失函数-Lasso 和regression2.2.2 损失函数-Lasso2.2.3 损失函数-regression2.2.4 Regression岭回归-矩阵验证2.2.5 Regression岭回归-导数验证 3. 迭代和随机…

人工智能的研究途径与方法

开篇 本文是学习《人工智能导论》这本书的笔记&#xff08;后续会持续更新&#xff09;。 正篇 心理模拟&#xff0c;符号推演 “心理模拟&#xff0c;符号推演”就是从人脑的宏观心理层面入手&#xff0c;以智能行为的心理模型为依据&#xff0c;将问题或知识表示成某种逻辑网…