spring基础--依赖注入的三种方式
1、使用@Autwired通过class字段注入值
让我们从定义两个对象的类开始:Person和Parrot.
@Component
public class Parrot {
private String name = "Koko";
// Omitted getters and setters
@Override
public String toString() { return "Parrot : " + name; }
}
我们指示Spring从其上下文中为该字段提供一个值 。Spring创建了两个bean,Person和Parrott,并将鹦鹉对象注入到类型为Person的bean的 字段中。
Person类的定义:
@Component
public class Person {
private String name = "Ella";
//我们用@Autwire注释该字段,指示Sp ring从其上下文中注入适当的值。
@Autowired
private Parrot parrot;
// Omitted getters and setters
}`
我已经使用构造型注释在此示例的Spring上下文中添加了bean。我本可以使用@ Bean定义bean,但在实际场景中,最常见的情况是,您会遇到将@Autwired与构造型注释一起使用
Configuration类的定义:
@Configuration
@ComponentScan(basePackages = "beans")
public class ProjectConfig { }
Main类的定义:
public class Main{
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext (ProjectConfig.class);
Person p = context.getBean(Person.class);
System.out.println("Person's name: " + p.getName());
System.out.println("Person's parrot: " + p.getParrot());
}
} T
输出:
Person's name: Ella
Person's parrot: Parrot : Koko
缺点:
不能选择将该字段设为final字段
@Component
public class Person {
private String name = "Ella";
@Autowired
private final Parrot parrot;
}
这不能编译。如果没有初始值,则不能定义final字段。
2、使用@Autwired通过构造函数注入值
当Spring创建Bean时,向对象属性注入值的第二种选择是使用定义实例的类的构造函数。这种方法是生产代码中最常用的方法。它使您能够将字段定义为final, 确保在Spring初始化它们之后没有人可以更改它们的值。
3、通过setter使用依赖项注入
您不会经常发现开发人员使用setter进行依赖注入的方法。这种方法弊大于利:阅读起来更具挑战性,不允许您确定final字段,也不能帮助您简化测试。
@Component
public class Person {
private String name = "Ella";
private Parrot parrot; // Omitted getters and setters
@Autowired
public void setParrot(Parrot parrot) {
this.parrot = parrot;
}
}
参考书籍
Spring Start Here (manning.com)
转载自:https://juejin.cn/post/7070135939288268814