使用@Autowired对set方法参数是map的注入

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注入

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值