7.笔记JAVASpring框架学习——Bean配置独立的集合属性
l 使用基本的集合标签定义集合时, 不能将集合作为独立的 Bean 定义, 导致其他 Bean 无法引用该集合, 所以无法在不同 Bean 之间共享集合.
l 可以使用 utilschema 里的集合标签定义独立的集合 Bean. 需要注意的是, 必须在 <beans> 根元素里添加 util schema 定义
需要导入schema/util
在app.xml定义如下:
<bean id="car"class="Car">
<constructor-arg value="KUGA"index="1"></constructor-arg>
<constructor-arg value="ChangAnFord"index="0"></constructor-arg>
<constructor-arg value="250000"type="float"></constructor-arg>
</bean>
<bean id="car2"class="Car">
<constructor-arg value="KUGA2"index="1"></constructor-arg>
<constructor-arg value="ChangAnFord2"index="0"></constructor-arg>
<constructor-arg value="2500002"type="float"></constructor-arg>
</bean>
<util:list id="cars">
<ref bean="car"/>
<ref bean="car2"/>
</util:list>
<bean id="user"class="User">
<property name="cars"ref="cars"/>
</bean>
修改User.java如下:
import java.util.List;
import java.util.Map;
public class User {
privateString userName;
privateList<Car> cars;
privateString wifeName;
publicString getWifeName() {
returnwifeName;
}
publicvoid setWifeName(String wifeName) {
System.out.println("setWifhName:" + wifeName);
this.wifeName= wifeName;
}
publicString getUserName() {
returnuserName;
}
publicvoid setUserName(String userName) {
this.userName= userName;
}
publicList<Car> getCars() {
returncars;
}
publicvoid setCars(List<Car> cars) {
this.cars= cars;
}
publicUser() {
System.out.println("User'sConstrutor...");
}
@Override
publicString toString() {
return"User [userName=" + userName + ", cars=" + cars +"]";
}
publicvoid init(){
System.out.println("initmethod...");
}
publicvoid destroy(){
System.out.println("destroymethod...");
}
}
在main.java中如下:
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
publicstatic void main(String[] args) {
//1.创建 Spring 的 IOC 容器
ApplicationContextapx = new ClassPathXmlApplicationContext("app.xml");
Useruser = (User) apx.getBean("user");
System.out.println(user);
}
}
执行如下:
User'sConstrutor...
User[userName=null, cars=[Car [company=ChangAnFord, brand=KUGA, maxSpeed=0,price=250000.0], Car [company=ChangAnFord2, brand=KUGA2, maxSpeed=0,price=2500002.0]]]