一、说明
constructor-arg:通过构造函数注入。
property:通过setter对应的方法注入。
二、property使用实例
1、Model代码:
public class Person {
private String name;
private int age;
private String className;
private String grade;
private List<Person> friends = new ArrayList<>();
public List<Person> getFriends() {
return friends;
}
public void setFriends(List<Person> friends) {
this.friends = friends;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String toString(){
return "Person [name=" + name + ", classname=" + className +", age=" + age+", grade=" + grade+", friends=
" +friends+ "]";
}
}
2、xml配置:
<bean id="person" class="models.Person">
<property name="age" value="22"/> //通过setXXX方法,所以Person对象属性不用全部设置,classname和grade未设置
<property name="name" value="liuzg"/>
<property name="friends"> //通过ref 传入已经初始化的bean wangxin和lirifeng
<list> //liuzg有两个朋友 wangxin和lirifeng
<ref bean="wangxin"/> //local只能在同一个XML中实现id引入,而bean可以跨XML文件引入,同时bean可以根据name属性进行引用,使用范围明显较广,更强大。
<ref bean="lirifeng"/>
</list>
</property>
</bean>
<bean id="wangxin" class="models.Person">
<property name="age" value="22"/>
<property name="name" value="wangxin"/>
</bean>
<bean id="lirifeng" class="models.Person">
<property name="age" value="22"/>
<property name="name" value="lirifeng"/>
</bean>
三、constructor-arg使用实例
1、Model代码:
public class Student {
private String name;
private int age;
private String className;
private String grade;
private List<Person> friends = new ArrayList<>();
public Student() {
}
public Student(String name,int age,String className,String grade,List<Person> friends){
this.friends = friends;
this.name = name;
this.age = age;
this.className = className;
this.grade = grade;
}
public String toString(){
return "student [name=" + name + ", classname=" + className +", age=" + age+", grade=" + grade+", friends=
" +friends+ "]";
}
}
2.xml配置
<bean id="liangyuqi" class="models.Student">
<constructor-arg index="0" value="liangyuqi"/> //通过构造函数,需根据函数形参 全部设置
<constructor-arg name="age" value="18"/> //可以根据index或者name设置属性,下标从0开始。boolean的值既可以用0/1填充,也可以用true/false填充。
<constructor-arg index="2" value="1401"/>
<constructor-arg index="3" value="95"/>
<constructor-arg index="4" ref="person"/>
</bean>
四、Test
1.测试代码
public class MyTest {
public void testSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("test.xml"); //1.读取spring初始化的配置文件
Object p = context.getBean("liangyuqi"); //2.根据bean获取Student实现类对象 p
System.out.println(p);
}
}
2.输出结果 : liangyuqi的朋友有liuzg,以及显示liuzg的friends set wnagxin,lirifeng