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

本文主要是介绍@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

这篇关于@Autowired 和 @Resource区别,简单测试容器中多个相同bean的情况的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1046546

相关文章

hevc和H.264格式的区别

HEVC(High Efficiency Video Coding)和H.264(也称为Advanced Video Coding,AVC)都是视频压缩标准,但它们之间存在一些显著的区别,主要集中在压缩效率、资源需求和兼容性方面。 压缩效率 HEVC,也被称为H.265,提供了比H.264更高的压缩效率。这意味着在相同的视频质量下,HEVC能够以大约一半的比特率进行编码,从而减少存储空间需求和

一份LLM资源清单围观技术大佬的日常;手把手教你在美国搭建「百万卡」AI数据中心;为啥大模型做不好简单的数学计算? | ShowMeAI日报

👀日报&周刊合集 | 🎡ShowMeAI官网 | 🧡 点赞关注评论拜托啦! 1. 为啥大模型做不好简单的数学计算?从大模型高考数学成绩不及格说起 司南评测体系 OpenCompass 选取 7 个大模型 (6 个开源模型+ GPT-4o),组织参与了 2024 年高考「新课标I卷」的语文、数学、英语考试,然后由经验丰富的判卷老师评判得分。 结果如上图所

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

LeetCode11. 盛最多水的容器题解

LeetCode11. 盛最多水的容器题解 题目链接: https://leetcode.cn/problems/container-with-most-water 示例 思路 暴力解法 定住一个柱子不动,然后用其他柱子与其围住面积,取最大值。 代码如下: public int maxArea1(int[] height) {int n = height.length;int

SpringBoot集成Netty,Handler中@Autowired注解为空

最近建了个技术交流群,然后好多小伙伴都问关于Netty的问题,尤其今天的问题最特殊,功能大概是要在Netty接收消息时把数据写入数据库,那个小伙伴用的是 Spring Boot + MyBatis + Netty,所以就碰到了Handler中@Autowired注解为空的问题 参考了一些大神的博文,Spring Boot非controller使用@Autowired注解注入为null的问题,得到

亮相WOT全球技术创新大会,揭秘火山引擎边缘容器技术在泛CDN场景的应用与实践

2024年6月21日-22日,51CTO“WOT全球技术创新大会2024”在北京举办。火山引擎边缘计算架构师李志明受邀参与,以“边缘容器技术在泛CDN场景的应用和实践”为主题,与多位行业资深专家,共同探讨泛CDN行业技术架构以及云原生与边缘计算的发展和展望。 火山引擎边缘计算架构师李志明表示:为更好地解决传统泛CDN类业务运行中的问题,火山引擎边缘容器团队参考行业做法,结合实践经验,打造火山

Eclipse+ADT与Android Studio开发的区别

下文的EA指Eclipse+ADT,AS就是指Android Studio。 就编写界面布局来说AS可以边开发边预览(所见即所得,以及多个屏幕预览),这个优势比较大。AS运行时占的内存比EA的要小。AS创建项目时要创建gradle项目框架,so,创建项目时AS比较慢。android studio基于gradle构建项目,你无法同时集中管理和维护多个项目的源码,而eclipse ADT可以同时打开

回调的简单理解

之前一直不太明白回调的用法,现在简单的理解下 就按这张slidingmenu来说,主界面为Activity界面,而旁边的菜单为fragment界面。1.现在通过主界面的slidingmenu按钮来点开旁边的菜单功能并且选中”区县“选项(到这里就可以理解为A类调用B类里面的c方法)。2.通过触发“区县”的选项使得主界面跳转到“区县”相关的新闻列表界面中(到这里就可以理解为B类调用A类中的d方法

自制的浏览器主页,可以是最简单的桌面应用,可以把它当成备忘录桌面应用

自制的浏览器主页,可以是最简单的桌面应用,可以把它当成备忘录桌面应用。如果你看不懂,请留言。 完整代码: <!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><ti

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python