【问题标题】:Does SpringBoot enforce Dependency Inversion design principle? And is this a good example of that?Spring Boot 是否强制执行依赖倒置设计原则?这是一个很好的例子吗?
【发布时间】:2021-01-30 16:14:55
【问题描述】:

所以我知道依赖倒置代表了 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;
    }

谢谢!

【问题讨论】:

    标签: java spring spring-boot model-view-controller solid-principles


    【解决方案1】:

    是的。依赖注入,在这种情况下具体是构造函数注入,是依赖倒置的一个很好的例子,也是控制倒置的一个很好的例子.这些概念都可以用hierarchy来描述。

    使用像 Spring 这样的 DI 容器可能是实现依赖倒置的最简单也是最常见的方法。请注意,如果InterviewController 只有一个构造函数,您甚至不需要将其注释为@Autowired。 Spring Boot 仍然会知道该怎么做。

    【讨论】:

      【解决方案2】:

      您的代码非常好,但您可以删除@Autowired。从 Spring 4.2 开始,在构造函数中使用依赖注入时没有必要。

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

      顺便说一句,像你一样使用带有构造函数而不是属性的 DI 是一种很好的做法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-27
        • 2015-10-30
        • 2012-05-09
        相关资源
        最近更新 更多