Spring Boot依赖注入的 3 种方式
Spring Boot 依赖注入的方式主要有以下三种:
- 构造函数注入
- Setter 方法注入
- 字段注入(不推荐)
以下是这三种方式的示例代码:
- 构造函数注入
@Component
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
// ...
}
- Setter 方法注入
@Component
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
// ...
}
- 字段注入(不推荐)
@Component
public class MyService {
@Autowired
private MyRepository myRepository;
// ...
}
注意:推荐使用构造函数注入,因为这种方式可以保证依赖不会为 null,且对象在构造后即处于可用状态。
评论已关闭