java使用@Autowired对方法参数是map的注入
最近在项目中看到对set方法直接使用@Autowired,接收参数是一个Map<String,类名称>
集合,一时没搞懂接收的map的值是从哪里注入的,经过上网查资料与试验终于明白:如果注入的参数是一个map,spring会将所有注入是map的value指定类的bean聚到一起,组成一个map当成参数注入
举例说明
假设有A,B两个接口,每个接口分别有A1,A2,A3 和B1,B2,B3三个实现类,在spring配置文件中将所有实现类注入,有一个工具C,其中有个方法是使用@Autowired注解的setA(Map<String,A> map),当程序启动后,spring会默认将类型是A的所有bean组成map注入,并且key是其类名称首字母小写
代码如下
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
default-autowire="byName">
<!-- A的实现类 -->
<bean id="1236" class="com.xx.test.A1"></bean>
<bean id="3217" class="com.xx.test.A2"></bean>
<bean id="4231" class="com.xx.test.A3"></bean>
<!-- B的实现类 -->
<bean id="1231" class="com.xx.test.B1"></bean>
<bean id="5126" class="com.xx.test.B2"></bean>
<bean id="4128" class="com.xx.test.B3"></bean>
</beans>
注入map的demo文件
@Component
public class Demo {
private static Map<String, A> aMap = new HashMap<>();
private static Map<String, B> bMap = new HashMap<>();
@Autowired
public void setA(Map<String, A> map) {
Demo.aMap = map;
System.out.println(map);
}
@Autowired
public void setB(Map<String, B> map) {
Demo.bMap = map;
System.out.println(map);
}
}
A,B接口及实现类无任何逻辑,只是定义
@Component
public interface A {
}
@Component
public class A1 implements A {
}
@Component
public interface B {
}
@Component
public class B1 implements B {
}
没有想象的那么复杂,只要注入了bean,spring就会自动将注入的bean给组成map注入