Spring的四种依赖注入方式

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方便

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值