java - SpringBoot 是否强制执行依赖倒置设计原则?这是一个很好的例子吗?
问题描述
所以我知道依赖倒置代表了 SOLID 设计原则中的 D,我之前使用 SpringBoot 编写了一个 web 应用程序,想知道这个代码示例是否显示了一个很好的依赖倒置原则的例子,或者没有帮助我理解这一点正确的概念。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
/**
* Provides a set of methods for serving and handling Interview data.
*/
@Controller
@SessionAttributes(names = {"users"})
public class InterviewController {
private final InterviewAuditor interviewAuditor;
private final AthleteAuditor athleteAuditor;
/**
* Injects all the needed auditors to talk to the database.
*
* @param interviewAuditor - the interview Auditor.
* @param athleteAuditor - the athlete Auditor.
*/
@Autowired
public InterviewController(InterviewAuditor interviewAuditor, AthleteAuditor athleteAuditor) {
this.interviewAuditor = interviewAuditor;
this.athleteAuditor = athleteAuditor;
}
谢谢!
解决方案
是的。依赖注入,在这种情况下特别是构造函数注入,是依赖反转的一个很好的例子,也是控制反转的一个很好的例子。这些概念都可以用层次结构来描述。
使用像 Spring 这样的 DI 容器可能是实现依赖倒置的最简单,当然也是最常见的方法。请注意,如果InterviewController
只有一个构造函数,您甚至不需要将其注释为@Autowired
. Spring Boot 仍然会知道该怎么做。
推荐阅读
- python - 我对我的“GPU”是否在我的环境中工作感到困惑?
- javascript - 在聊天 API 中找到了一些 JSON 逻辑运算符,这是如何工作的
- python - 使用哪一个:super() 或 self.function(),函数在父类中定义
- amazon-quicksight - amazon quicksight 是否可以在 5 分钟或不到 1 小时内刷新数据集
- javascript - 在 Django 项目的 javascript 文件中包含 javascript 文件
- spring-kafka - 如果消息是 GenericRecord,如何在 KafkaListener 方法中提取消息头详细信息
- javascript - 需要从 Google Apps 脚本查询 Google Sheet 以获取特定数据
- vuetify.js - Vuetify VDataTable 处理每页更新的项目
- google-sheets - 自动更改或查询功能谷歌表
- git - git - 这个项目中的 git 历史有什么问题以及如何与它进行上游合并