首页 > 解决方案 > 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;
    }

谢谢!

标签: javaspringspring-bootmodel-view-controllersolid-principles

解决方案


是的。依赖注入,在这种情况下特别是构造函数注入,是依赖反转的一个很好的例子,也是控制反转的一个很好的例子。这些概念都可以用层次结构来描述。

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


推荐阅读