三种依赖注入方式
测试用的实体类:
package SpringMb.entity;
public class Student {
private String name;
private int id;
private Teacher teacher;
}
1.set注入
set注入:将对象关联,通过当前对象的set方法注入给当前属性对象
使用set注入,首先就要在实体类中写好set()方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
然后在spring配置文件里新建一个<bean>
id对应的就是这个bean的id,class对应的就是要注入的实体类
在<bean>
中设置属性<property>
,name为属性的名称,value为要注入的值。
若要注入的是另一个实体类,则是使用ref指向另一个实体类bean的id
<bean id="student" class="SpringMb.entity.Student">
<property name="name" value="hun"/>
<property name="id" value="1"/>
<property name="teacher" ref="teacher"/>
</bean>
2.构造器注入
构造方法注入:将当前对象关联,通过当前对象的构造方法注入给当前属性对象
要用到构造器注入,首先就要先写好构造方法
public Student(String name, int id) {
this.name = name;
this.id = id;
}
同样也是在spring配置文件,与set注入比较相似
默认是按照构造器里赋值顺序依次赋值
<bean id="student" class="SpringMb.entity.Student">
<constructor-arg value="hun"/>
<constructor-arg value="1"/>
</bean>
可以使用index来指定是构造器中的第几个,注意是从0开始
<constructor-arg index="0" value="hun"/>
可以用type和name来指定注入类型和画要注入的变量名
<constructor-arg name="name" type="String" value="hun"/>
3.p命名空间
前提要要有一个无参构造方法
public Student() {
}
<bean id="student" class="SpringMb.entity.Student" p:id="1" p:name="hun"></bean>
使用注解实现依赖注入
使用注解,首先要在spring配置文件里开启扫描器
base-package对应的就是包名
<context:component-scan base-package="SpringMb"/>
@Component("student")
public class Student {
@Value("hun")
private String name;
@Value("1")
private int id;
}
@Component("student")
就等于:
<bean id="student" class="SpringMb.entity.Student">