spring - 抽象类和接口的依赖注入
问题描述
我们可以像下面给出的代码那样将抽象类和接口属性的依赖注入到我们想要的类中吗?
abstract class Parent { }
interface Heritage { }
class Child
{
@Autowired private Parent parent;
@Autowired private Heritage heritage;
}
解决方案
使用属性注入(又名 Setter 注入)或字段注入来防止注入依赖项。这些做法导致了时间耦合。相反,您应该只使用构造函数注入作为 DI 的实践,因为:
- 构造函数可以保证提供所有依赖项,防止时间耦合
- 构造函数静态声明类的依赖项
- 允许创建类的实例而不需要任何工具(例如 DI 容器)来构造该类型
- 当一个组件只有一个构造函数时(这是一种很好的做法),它可以避免使用任何特殊的框架特定属性来标记类,例如
@Autowired
.
使用构造函数注入时,该类将如下所示:
class Child
{
private Parent parent;
private Heritage heritage;
public Child(Parent parent, Heritage heritage) {
if (parent == null) throw new NullErrorException();
if (heritage == null) throw new NullErrorException();
this.parent = parent;
this.heritage = heritage;
}
}
推荐阅读
- cassandra - 从 Apache Cassandra 到 Ignite 的连接器
- redirect - 带有重定向的drupal 7网站垃圾邮件
- c++ - 模板类和好友模板函数
- vba - 我可以使用 VBA 在电子邮件中添加 RangetoHTML(rng) 然后 strbody 吗?
- javascript - for循环和setInterval,幻灯片放映
- c++ - 是否可以使用将模板参数作为模板参数的类型?
- python - python读取文件,打印以特定字符串开头的部分行
- ruby-on-rails - 在 rails 中下载由 XlsxWriter 创建的 XLSX 文件
- ios - SceneKit 子节点旋转
- reactjs - 在redux连接函数中将多个函数传递给mapDispatchToProps