Spring的四种依赖注入方式
1.依赖构造器的依赖注入(constructor)
创建Person类,将Person 类通过Student的构造器注入到Student中
public class Person {
Private String name;
public void write(name){
System.out.println(name);
}
}
创建Student类,创建依赖person类的构造器
public class Student {
private int id;
private String name;
private Person person;
public Student(Person person) {
This.person = person;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
如果要调用studen类就要创建person 实例,也就是student类依赖person类,然后我们接下来看如何将这个person类通过构造器用spring容器注入到student类的:
2.依赖设置函数的依赖注入(set)
还是上面的两个类,接下来我们通过setPerson注入person
3.依赖自动装配的依赖注入(autowire)
这是依据autowire的自动装配
这个是测试类:
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext(“applicationContext.xml”);
Student stu=context.getBean(“stu”,Student.class);
stu.getPerson().write();
}
4.依赖注解的依赖注入()
Spring默认不开启注解,需要开启注解并在表头添加context的信息
然后为person类添加注解,类似于在spring容器注册了名字为person,类地址为
com.iotek.bean.person的bean;
@Component(“student”)
public class Student {
}
同理为Student 注册bean信息
@Component(“student”)
public class Student {
@Autowired
private Person person;
//@Autowired:注解的使用(不用再写set方法),我们就可以直接在student类里使用person对象了,这是最常用的方法哦
public void read(){
person.write();
}
}
需要注意的是, @Autowired和@Resource,@Autowired默认byType自动装配,只适用于该类没有同名类的情况,@Resource默认按照名字自动装配,但是明显没有@Autowired方便