如何在spring中配置集合供多个Bean使用

一:Utility   Scheme

1.使用基本的集合标签定义集合时,不能将集合作为独立的Bean定义,导致其他Bean无法引用该集合,所以无法在不同Bean之间

共享集合。

2.可以使用Utility  Scheme里的集合标签定义独立的集合Bean,需要的是在Beans根元素里添加Utility   Scheme定义。

二:如何配置独立的集合

1.导入Utility   Scheme定义。点击Namespaces,然后选择util

2. 配置单例的集合Bean和进行引用

<!--配置单例的集合Bean,以供多个集合bean进行引用,需要注意的是要先导入util命名空间  -->
	<util:list id="cars">
		<ref bean="car"/>
		<ref bean="car2"/>
	</util:list>
	
	<bean id="person4" class="com.collection.dhx.Person">
		<property name="name" value="Jack"></property>
		<property name="age" value="21"></property>
		<!-- 在这里引用公共的集合Bean(cars) -->
		<property name="cars" ref="cars"></property>
	</bean>

3.在Main类中打印

    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    Person p=(Person) ctx.getBean("person4");
    System.out.println(p);

猜你喜欢

转载自blog.csdn.net/qq_39093474/article/details/85254462