public class TestUtil {
private List<String> list;
private Set<String> set;
private Map<String, String> map;
private List<User> userList;
// getter/setter
}
<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"/>
@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;
}
@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> | 對應類型數組 | 固定長度 |
<entry key="..."> 鍵只能是 String,複雜鍵需 <entry key-ref="bean"> 或 SpELnew ArrayList<>()Spring 提供聲明式集合注入,XML 標簽語義清晰,註解配合 SpEL/@Qualifier 同樣強大。掌握 <list/set/map/props/array>、merge 合併、對象元素 ref、SpEL 集合字面量,可覆蓋 99% 集合注入場景。