【Spring】@Autowired and @Resource

本文探讨了Spring框架中@Autowired和@Resource注解的默认行为,并通过实验验证了它们如何按名称或类型进行自动装配。此外,还介绍了如何使用@Qualifier解决类型匹配不唯一的问题。
Given that Spring can autowire either by type or by name, it is always confusing to me that what is the default behavior when using annocation @Autowired or @Resource to do the autowire. Therefore, I made an experiment to help clear out confusion. Here are some of my findings:
      1. By default @Autowired and @Resource will first use field name or parameter name to autowire bean with the same name as bean id. If it can't find any matching bean id, then it will autowire by type. 
      2. When autowire by type, for certain type, there must be only one bean existing in the application context. Otherwise, Spring will throw exception like: No unique bean of type [com.ms.junz.domain.User] is defined: expected single matching bean but found 2: [user1, user]
      3. If your field name is independent of bean id and there might be multiple beans with the same type, you can use either@Qualifier("beanId") together with @Autowired, or @Resource(name="beanId") to explicitly tell Spring which bean to autowire. Then, Spring wouldn't complain any longer.
 



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值