1. List 注入:
XML配置方式:
<bean id="exampleBean" class="com.example.ExampleBean">
<property name="listProperty">
<list>
<value>item1</value>
<value>item2</value>
<value>item3</value>
</list>
</property>
</bean>
Java配置方式:
@Configuration
public class AppConfig {
@Bean
public ExampleBean exampleBean() {
ExampleBean exampleBean = new ExampleBean();
exampleBean.setListProperty(Arrays.asList("item1", "item2", "item3"));
return exampleBean;
}
}
2. Set 注入:
XML配置方式:
<bean id="exampleBean" class="com.example.ExampleBean">
<property name="setProperty">
<set>
<value>item1</value>
<value>item2</value>
<value>item3</value>
</set>
</property>
</bean>
Java配置方式:
@Configuration
public class AppConfig {
@Bean
public ExampleBean exampleBean() {
ExampleBean exampleBean = new ExampleBean();
exampleBean.setSetProperty(new HashSet<>(Arrays.asList("item1", "item2", "item3")));
return exampleBean;
}
}
3. Map 注入:
XML配置方式:
<bean id="exampleBean" class="com.example.ExampleBean">
<property name="mapProperty">
<map>
<entry key="key1" value="value1"/>
<entry key="key2" value="value2"/>
<entry key="key3" value="value3"/>
</map>
</property>
</bean>
Java配置方式:
@Configuration
public class AppConfig {
@Bean
public ExampleBean exampleBean() {
ExampleBean exampleBean = new ExampleBean();
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
exampleBean.setMapProperty(map);
return exampleBean;
}
}
4. 数组注入:
XML配置方式:
<bean id="exampleBean" class="com.example.ExampleBean">
<property name="arrayProperty">
<array>
<value>item1</value>
<value>item2</value>
<value>item3</value>
</array>
</property>
</bean>
Java配置方式:
@Configuration
public class AppConfig {
@Bean
public ExampleBean exampleBean() {
ExampleBean exampleBean = new ExampleBean();
exampleBean.setArrayProperty(new String[]{"item1", "item2", "item3"});
return exampleBean;
}
}
在这些例子中,ExampleBean 类包含了 List、Set、Map、数组等类型的属性,并通过Spring的依赖注入机制进行集合的注入。注意,在实际的应用中,可以根据需求选择适合场景的集合类型。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6945/Spring