0

So I understand that Dependency Inversion represents the D in SOLID design principles, and I have previously written a web-application using SpringBoot and was wondering if this code example shows a good example of the Dependency Inversion principle in action or not to help me understand this concept properly.

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;
    }

Thanks!

Jack Goodwin
  • 99
  • 1
  • 6

2 Answers2

0

Yes. Dependency injection, which in this case is constructor injection specifically, is a good example of dependency inversion, and also a good example of inversion of control. These concepts can all be described in terms of a hierarchy.

Using a DI container like Spring is probably the easiest and certainly the most common approach to achieving dependency inversion. Note that if InterviewController has only one constructor, you don't even need to annotate it as @Autowired. Spring Boot will still know what to do.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
0

Your code is pretty good, but you can remove @Autowired. It is not necessary when using Dependency Injection with constructor since Spring 4.2.

I don't know if InterviewAuditor and AthleteAuditor are interface but it's a good practice to inject interface (if it exists of course) to have flexibility. Thus you can reuse the same class with different dependencies (different implementation).

By the way it's good practice to use DI with constructor instead of property as you did.

vmargerin
  • 94
  • 2