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仍然知道该怎么做。

你的代码很好,但是你可以删除@Autowired。从Spring 4.2开始,在构造函数中使用依赖注入就不需要了。

我不知道InterviewAuditor和AthleteAuditor是否是接口,但注入接口(如果它当然存在)以具有灵活性是一个很好的实践。因此,您可以使用不同的依赖项(不同的实现)重用相同的类。

顺便说一下,像你那样使用带有构造函数而不是属性的DI是很好的实践。

最新更新