Spring注解的(List&Map)特殊注入功能
一、先看一个示例演示:spring注解的一个特殊的注入功能。
首先,是定义一个接口,3个实现类。
public interface GreetService {
public String sayHello(String name);
}
@Service("china")
public class ChinaGreetServiceImpl implements GreetService {
@Override
public String sayHello(String name) {
return "你好";
}
}
@Service("japan")
public class JapanGreetServiceImpl implements GreetService {
@Override
public String sayHello(String name) {
return "亚麻得";
}
}
@Service("usa")
public class UsaGreetServiceImpl2 implements GreetService {
@Override
public String sayHello(String name) {
return "hello";
}
}
下面看到代码中有直接注入一个List和一个Map的。示例代码如下:
GreetController代码:
@RestController
@RequestMapping("/greet")
public class GreetController { @Autowired
private List<GreetService> greetServiceList; @Autowired
private Map<String, GreetService> greetServiceMap; @RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
public String getbook5(@ApiParam("id编号") @PathVariable("id") Long id) {
for (Map.Entry<String, GreetService> entry : greetServiceMap.entrySet()) {
System.out.println(entry.getValue().sayHello("" + id));
}
System.out.println("==list====");
for (GreetService greetService : greetServiceList) {
System.out.println(greetService.sayHello("" + id));
} return "" + id;
} }
最后在调试List的时候突然灵感一闪,如果只有一个对象那么List里面的值不就只有一个吗。于是开始测试验证,结果发现的确如此。当实例化一个GreetController之后,另外一个类采用泛型注入List,Spring竟然成功的将实例化的对象放入List之中。思路打开之后,针对Map的就更好说了。Spring会将service的名字作为key,对象作为value封装进入Map。
运行之后,访问http://127.0.0.1:8091/greet/test/1执行结果如下:

原来,在不知不觉中Spring已经帮我们做了很多事情,只是我们不知道而已。
二、@Autowired 注入集合类型
从spring-beans-4.3.14.RELEASE.jar的源码可以看看到如下:
在org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DependencyDescriptor, String, Set<String>, TypeConverter) 方法中发现了原因。

对于@Autowired声明的数组、集合类型,spring并不是根据beanName去找容器中对应的bean,而是把容器中所有类型与集合(数组)中元素类型相同的bean构造出一个对应集合,注入到目标bean中。对应到上问配置文件中,就是把容器中所有类型为java.lang.String的bean放到新建的Set中,然后注入到Manager bean中。也就是把resourcePackage和resourceLoaction这两个String注入了,导致上面的输出结果。
在spring reference中也发现相关说明。
If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to
the specific collection or map bean by unique name.
@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument.
As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.
从上面的说明中找到解决办法就是注入集合类型不要使用@Autowired,而使用@Resource注解。同时Spring官方也是不推荐使用@Autowired的。
Spring注解的(List&Map)特殊注入功能的更多相关文章
- spring注解不支持静态变量注入
spring注解不支持静态变量注入:今天敲代码 自动配置 配置: Animal.java package study01_autoconfig.beanConfig; import org.spri ...
- spring注解(Component、依赖注入、生命周期、作用域)
1.注解 注解就是一个类,使用@加上注解名称,开发中可以使用注解取代配置文件 2.@Component 取代<bean class="">,@Component 取代 ...
- 使用spring注解——定义bean和自动注入
对于java bean的定义和依赖配置,使用xml文件真心是不方便. 今天学习如何用注解,解决bean的定义和注入. 常用注解: 1.自动注入:@Resources,@Autowired 2.Bean ...
- Spring注解问题,[action中注入service失败
pring-mvc.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...
- Spring-Context的注解实现依赖注入功能
使用Spring-Context的注解实现依赖注入功能. Demo要点: 本例子中主要使用Annotation功能来实现对MoviceService的注入.我们将Cinema.java的头部标注为@C ...
- 使用Spring注解注入属性
本文介绍了使用Spring注解注入属性的方法.使用注解以前,注入属性通过类以及配置文件来实现.现在,注入属性可以通过引入@Autowired注解,或者@Resource,@Qualifier,@Pos ...
- SpringBoot的注解注入功能移植到.Net平台(开源)
*:first-child { margin-top: 0 !important; } .markdown-body>*:last-child { margin-bottom: 0 !impor ...
- 【Spring】的【Bean】管理(注解)【四个相同功能的注解】
[Spring]的[Bean]管理(注解)[四个相同功能的注解] 注解:代码里面特殊的标记,使用注解也可以完成一些相关的功能. 注解写法:@注解名称(属性名称=属性值) 注解使用在类.方法.属性上面 ...
- spring注解方式在一个普通的java类里面注入dao
spring注解方式在一个普通的java类里面注入dao @Repositorypublic class BaseDaoImpl implements BaseDao {这是我的dao如果在servi ...
随机推荐
- 使用CSS去除 去掉超链接的下划线方法
我们可以用CSS语法来控制超链接的形式.颜色变化,为什么链接一定要使用下划线和颜色区分呢? 其主要原因主要是考虑到 1.视力差的人 2.色盲的人 ... 下面我们做一个这样的链接:未被点击时超链接 ...
- 解密优秀博士成长史 ——微软亚洲研究院首届博士生学术论坛Panel讨论经验总结
编者按:有人说“一入博门深似海”,读博前应该做好哪些准备?作为一名博士生,应该有怎样的学术或职业规划?导师还是老板?怎样在师生关系上做到双赢?你是导师心目中优秀的博士生吗?相信以上问题在很多同学心中萦 ...
- Javascript:如何调用全局变量?
怎样使用全局变量呢? window.globalVariableName 参考: https://blog.csdn.net/zyz511919766/article/details/7276089
- OSX: diskutil命令-转换成自由空间并再对其分区
声明:本文涉及的操作非常可能会破坏你的系统文件,造成数据丢失.请谨慎模仿,一切后果作者均不承担不论什么责任. 目的: 尽管说比較熟悉diskutil命令和它的GUI前端程序磁盘工具(Disk Util ...
- springmvc学习笔记(12)-springmvc注解开发之包装类型參数绑定
springmvc学习笔记(12)-springmvc注解开发之包装类型參数绑定 标签: springmvc springmvc学习笔记12-springmvc注解开发之包装类型參数绑定 需求 实现方 ...
- Yelp面试题目
题目:FizzBuzz 从stdin得到数字N(<10^7),然后从打印出从1到N的数字.输出到stdout,假设数字是3的倍数的话就仅仅打印"Buzz",假设数字是5的倍数 ...
- 二:redis 的hash类型相关操作
=====================二种:hash类型================== 介绍:redis -> hash是一个string类型的field和value的映射表 hash ...
- fruitstrap 安装.app文件
1. 下载ipa的ios文件然后解压成.app的文件 2. 进入fruitstrap文件夹,copy .app文件到fruitstrap文件夹中 执行./fruitstrap -b umetrip.a ...
- mysql读写分离(主从复制)实现
mysql主从复制 怎么安装mysql数据库,这里不说了,仅仅说它的主从复制.过程例如以下: 主从最好都是同一种系统比方都是linux,或者都是windows,当然混合着也是能够成功,不解释了 1.主 ...
- Spring中的事务管理(学习笔记)
什么是事物? 事物是指逻辑上的一组操作,这组操作要么全部成功,要么全部失败. 事物的特性: 原子性.一致性.隔离性.持久性 Spring事务管理的高级接口: PlatformTransactionMa ...