一、说明
constructor-arg:通过构造函数注入。
property:通过setter对应的方法注入。
二、constructor-arg的使用示例
1、测试代码:
constructor-arg:通过构造函数注入。
property:通过setter对应的方法注入。
二、constructor-arg的使用示例
1、Model代码:
-
public class Student {
-
private Integer id;
-
private String name;
-
private List<String> dream;
-
private Map<String, Integer> score;
-
private boolean graduation;
-
-
public Student() {
-
}
-
-
public Student(Integer id, String name, List<String> dream,
-
Map<String, Integer> score, boolean graduation) {
-
this.id = id;
-
this.name = name;
-
this.dream = dream;
-
this.score = score;
-
this.graduation = graduation;
-
}
-
-
-
public String toString() {
-
return "Student [id=" + id + ", name=" + name + ", dream=" + dream
-
+ ", score=" + score + ", graduation=" + graduation + "]";
-
}
-
}
-
<bean id="student"class="com.rc.sp.Student">
-
<constructor-argname="id" value="1"/>
-
<constructor-argname="name" value="student"/>
-
<constructor-argname="dream">
-
<list>
-
<value>soldier </value>
-
<value>scientist </value>
-
<value>pilot </value>
-
</list>
-
</constructor-arg>
-
<constructor-argname="score">
-
<map>
-
<entrykey="math" value="90"/>
-
<entrykey="english" value="85"/>
-
</map>
-
</constructor-arg>
-
<constructor-argname="graduation" value="false"/>
-
</bean>
三、property的使用示例
1、Model代码:
-
public class Teacher {
-
private Integer id;
-
private String name;
-
-
public Integer getId() {
-
return id;
-
}
-
-
public void setId(Integer id) {
-
this.id = id;
-
}
-
-
public String getName() {
-
return name;
-
}
-
-
public void setName(String name) {
-
this.name = name;
-
}
-
-
-
public String toString() {
-
return "Teacher [id=" + id + ", name=" + name + "]";
-
}
-
}
-
<bean id="teacher" class="com.rc.sp.Teacher">
-
<property name="id" value="1"> </property>
-
<property name="name" value="teacher"> </property>
-
</bean>
1、测试代码:
-
public class Run {
-
public static void main(String[] args) {
-
ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
-
Student student = (Student) context.getBean( "student");
-
System.out.println(student);
-
Teacher teacher = (Teacher) context.getBean( "teacher");
-
System.out.println(teacher);
-
}
-
}
2、输出结果:
-
Student [id=1, name=student, dream=[soldier, scientist, pilot],score={math=90, english=85}, graduation=false]
-
Teacher [id=1, name=teacher]
-