问题描述
所以我明白依赖倒置代表了 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;
}
谢谢!
解决方法
是的。依赖注入,在本例中是构造函数注入,是依赖倒置的一个很好的例子,也是控制倒置的一个很好的例子.这些概念都可以用 hierarchy 来描述。
使用像 Spring 这样的 DI 容器可能是实现依赖倒置的最简单也是最常见的方法。请注意,如果 B
只有一个构造函数,您甚至不需要将其注释为 InterviewController
。 Spring Boot 仍然会知道该做什么。
你的代码很好,但你可以删除@Autowired。从 Spring 4.2 开始在构造函数中使用依赖注入时不需要。
我不知道InterviewAuditor 和AthleteAuditor 是否是接口,但是注入接口(当然如果存在的话)以获得灵活性是一个很好的做法。因此,您可以重用具有不同依赖项(不同实现)的同一个类。
顺便说一句,将 DI 与构造函数一起使用而不是像您那样使用属性是一种很好的做法。