首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 集合注入完全指南:List、Set、Map 與對象元素的 XML 與註解配置

     編輯:Java 綜合教學

場景:Bean 內部持有集合屬性

public class TestUtil {
    private List<String> list;
    private Set<String> set;
    private Map<String, String> map;
    private List<User> userList;
    // getter/setter
}

XML 配置:標準標簽

<bean id="testUtil" class="com.example.TestUtil">
    <!-- List: 有序、可重複 -->
    <property name="list">
        <list>
            <value>list 元素1</value>
            <value>list 元素2</value>
            <value>list 元素3</value>
        </list>
    </property>

    <!-- Set: 無序、去重 -->
    <property name="set">
        <set>
            <value>張三</value>
            <value>李四</value>
        </set>
    </property>

    <!-- Map: 鍵值對 -->
    <property name="map">
        <map>
            <entry key="key1" value="Java 從入門到精通"/>
            <entry key="key2" value="Java 開發實戰"/>
        </map>
    </property>

    <!-- List 注入對象 Bean -->
    <property name="userList">
        <list>
            <ref bean="user1"/>
            <ref bean="user2"/>
        </list>
    </property>
</bean>

<bean id="user1" class="com.example.User" p:name="Alice"/>
<bean id="user2" class="com.example.User" p:name="Bob"/>

註解配置:@Value + SpEL / @Autowired + @Qualifier

簡單集合:@Value + SpEL

@Component
public class TestUtil {
    @Value("#{'item1,item2,item3'.split(',')}")
    private List<String> list;

    @Value("#{new HashSet({'a','b'})}")
    private Set<String> set;

    @Value("#{{key1:'val1', key2:'val2'}}")
    private Map<String, String> map;
}

對象集合:@Autowired + @Qualifier / @Resource

@Component
public class TestUtil {
    @Autowired
    @Qualifier("userList")  // 或 @Resource(name="userList")
    private List<User> userList;
}

@Configuration
class Config {
    @Bean @Qualifier("userList")
    List<User> userList() {
        return Arrays.asList(new User("Alice"), new User("Bob"));
    }
}

測試驗證

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
TestUtil util = ctx.getBean(TestUtil.class);

util.getList().forEach(System.out::println);
util.getSet().forEach(System.out::println);
util.getMap().forEach((k,v) -> System.out.println(k + "=" + v));
util.getUserList().forEach(u -> System.out.println(u.getName()));

進階:集合合併與繼承

<bean id="parent" class="com.example.Parent">
    <property name="emails">
        <list><value>parent@test.com</value></list>
    </property>
</bean>

<bean id="child" class="com.example.Child" parent="parent">
    <property name="emails">
        <list merge="true">  <!-- 合併父集合 -->
            <value>child@test.com</value>
        </list>
    </property>
</bean>

結果:child.emails = [parent@test.com, child@test.com]。

常見類型對照表

集合接口XML 標簽默認實現類特性
List<list>ArrayList有序、可重複、下標訪問
Set<set>HashSet無序、唯一
Map<map>HashMap鍵值對、鍵唯一
Properties<props>Properties鍵值皆 String
Array<array>對應類型數組固定長度

避坑指南

  1. Map 鍵類型:XML <entry key="..."> 鍵只能是 String,複雜鍵需 <entry key-ref="bean"> 或 SpEL
  2. Set 去重依賴 equals/hashCode:注入對象元素時確保正確實現
  3. List 有序性:XML 定義順序即集合順序,LinkedHashSet 保持插入序
  4. 空集合 vs null:未配置集合屬性默認 null,需預防 NPE 或初始化 new ArrayList<>()
  5. 循環引用:集合中引用彼此的 Bean 會導致創建死循環 → 改用 Setter 注入或 @Lazy

總結

Spring 提供聲明式集合注入,XML 標簽語義清晰,註解配合 SpEL/@Qualifier 同樣強大。掌握 <list/set/map/props/array>、merge 合併、對象元素 ref、SpEL 集合字面量,可覆蓋 99% 集合注入場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved