一、在Spring框架中如何给属性赋值呢?
其实,就是DI(Dependency Injection)依懒注入。
二、如何DI呢?有几种方式
spring框架为我们提供了三种注入方式;
(1)set注入 (必须封装setXXX方法)
public class Person {
private Long pid; //包装类型
private String pname; //String类型
private Student student; //引用类型
private List lists; //集合
// 3.3.2.4. 集合
// 通过<list/>、<set/>、<map/>及<props/>元素可以定义和设置与Java Collection类型对应List、Set、Map及Properties的值。
public List getLists() {
return lists;
}
public void setLists(List lists) {
this.lists = lists;
}
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
applicationContext.xml文件如下:
<bean id="person" class="com.hlx.hello.set.Person">
<property name="pid" value="1001"/>
<property name="pname" value="菲菲"/>
<property name="student" ref="mystudent"/>
<property name="lists">
<list>
<value>aaa</value>
<value>ccc</value>
<ref bean="mystudent"/>
</list>
</property>
</bean>
<bean id="mystudent" class="com.hlx.hello.set.Student"></bean>
(2)构造方法注入 (必须封装构造方法)
public class Person {
private Long pid; // 包装类型
private String pname; // String类型
private Student student; // 引用类型
public Person(Long pid, String pname, Student student) {
super();
this.pid = pid;
this.pname = pname;
this.student = student;
}
public Person(Long pid, String pname) {
super();
this.pid = pid;
this.pname = pname;
}}
applicationContext.xml文件如下:
当参数为非字符串类型时,在配置文件中需要制定类型,如果不指定类型一律按照字符串类型赋值。
当参数类型不一致时,框架是按照字符串的类型进行查找的,因此需要在配置文件中制定是参数的位置
<!--
index :从0开始数;
type: 对应的具体数据类型(可写可不写)
value: 对应的值
ref :对应的引用类型
只能配置一个构造方法 -->
<bean id="person" class="com.hlx.hello.constructor.Person">
<constructor-arg index="0" type="java.lang.Long" value="1003"/>
<constructor-arg index="1" value="pop"/>
<constructor-arg index="2" ref="mystudent"/>
</bean>
(3)接口注入(接口注入不作要求忽略)