配置文件的根元素是beans,每个组件使用bean元素来定义,bean元素可以有许多属性,其中有两个是必须的:id和class。id表示组件的默认名称,class表示组件的类型。
一、区别
constructor-arg与property都是依赖注入的方式
constructor-arg:通过构造函数注入。 则property:通过setxx方法注入。
二、constructor-arg使用实例
1、Model代码:
public class Student {
private Integer id;
private String name;
private String className;
private List<String> dream;
private Map<String, Integer> score;
private boolean graduation;
public Student() {
}
public Student(Integer id, String name, String className, List<String> dream,
Map<String, Integer> score, boolean graduation) {
this.id = id;
this.name = name;
this.className=className;
this.dream = dream;
this.score = score;
this.graduation = graduation;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name +", className=" + className+ ", dream=" + dream + ", score=" + score + ", graduation=" + graduation + "]";
}
}
2、xml配置:
<!--通过构造函数,需根据函数值 全部设置-->
<bean id="student" class="com.xyai.Student">
<!-- 可以根据index或者name设置属性,下标从0开始 -->
<constructor-arg name="0" value="1"/>
<constructor-arg name="name" value="zyf"/>
<constructor-arg index="2" value="xyai"/>
<constructor-arg name="dream">
<list>
<value>value1</value>
<value>value2</value>
<value>value3</value>
</list>
</constructor-arg>
<constructor-arg name="score">
<map>
<entry key="key1" value="10"/>
<entry key="key2" value="20"/>
</map>
</constructor-arg>
<!-- boolean的值既可以用0/1填充,也可以用true/false填充 -->
<constructor-arg name="graduation" value="false"/>
</bean>
三、property使用实例
1、Model代码:
public class Teacher {
private Integer id;
private String name;
private List<User> users= new ArrayList<>();
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 List<User> getUsers() {
return Users;
}
public void setFriends(List<User> users) {
this.users = users;
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + ", users=" +users+ "]";
}
}
2、xml配置:
<bean id="teacher" class="com.xyai.Teacher">
<!-- 通过setXXX方法,所以Teacher对象属性不用全部设置,及id、name、users可设置可不设置-->
<property name="id" value="1"></property>
<property name="name" value="zyf"></property>
<property name="users">
<list>
<ref bean="xyai2"/>
<ref bean="xyai3"/>
</list>
</property>
<bean id="xyai2" class="com.xyai.Teacher">
<property name="id" value="2"/>
<property name="name" value="zyf"/>
</bean>
<bean id="xyai3" class="com.xyai.Teacher">
<property name="id" value="3"/>
<property name="name" value="zyf"/>
</bean>
</bean>
四、Test
1.测试代码
public class Test {
public static void main(String[] args) {
//1.读取spring初始化的配置文件
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
//2.根据bean获取Student实现类对象 student
Student student = (Student) context.getBean("student");
System.out.println(student);
Teacher teacher = (Teacher) context.getBean("teacher");
System.out.println(teacher);
}
}