使用@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注入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章