配置bean时,可以使用无参构造器加set方法配置,当然,也可以使用构造器配置,也就是使用带参数的构造器装配bean。
首先,定义两个类。
package com.cmm;
public class Phone {
private String brand;
private int price;
public Phone(String brand, int price) {
super();
this.brand = brand;
this.price = price;
}
@Override
public String toString() {
return "Phone [brand=" + brand + ", price=" + price + "]";
}
}
package com.cmm;
public class Person {
private Phone phone;
public Person(Phone phone) {
super();
this.phone = phone;
}
@Override
public String toString() {
return "Person [phone=" + phone + "]";
}
}
1、先使用普通的方法配置。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="hw" class="com.cmm.Phone">
<!--
index: 表示构造器参数的顺序,0 表示参数:brand,1表示参数:price
value: 表示参数的值,如果是引用,可以使用ref
-->
<constructor-arg index="0" value="hw"></constructor-arg>
<constructor-arg index="1" value="3000"></constructor-arg>
</bean>
<bean id="personA" class="com.cmm.Person">
<!--
name:表示参数的名字
type:表示参数的类型
ref:表示参数所引用的bean
-->
<constructor-arg name="phone" type="com.cmm.Phone" ref="hw"></constructor-arg>
</bean>
</beans>
2、使用c命名空间,c也就是:constructor的意思,也就是构造器命名空间。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="hw" class="com.cmm.Phone" c:brand="hw" c:price="3000">
</bean>
<bean id="personA" class="com.cmm.Person" c:phone-ref="hw"></bean>
</beans>
现在,使用xml装配bean的两种方法,已经都介绍了。
总结一下:
1、使用set方法,即属性方法配置。
2、使用带参数的构造器,即配置器方法配置。
可以使用普通的xml方法配置,也可以使用p空间与c空间配置。