0

I have an Service Class and a Controller Class:

@Service
public class StudentService {

    public List<Student> getStudents(){
        return List.of(new Student(1L,
                "Vitor",
                "email@gmail.com",
                LocalDate.of(1993, Month.JANUARY, 6),
                28));
    }
}

On the controller what is the difference (practical and/or theoretical) between the 2 implementations below? (Both works well on my tests)

1: @Autowired direct on the Service object.

@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public List<Student> getStudents(){
        return studentService.getStudents();
    }
}

2: @Autowired on the constructor

@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {

    private final StudentService studentService;

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public List<Student> getStudents(){
        return studentService.getStudents();
    }
}

Thanks.

vitorvr
  • 605
  • 1
  • 5
  • 19
  • 1
    Does this answer your question? https://stackoverflow.com/questions/40620000/spring-autowire-on-properties-vs-constructor/40620318 – Nicolas125841 Jul 20 '21 at 03:22
  • @Nicolas125841, missed that post. Answered. Thanks. – vitorvr Jul 20 '21 at 03:31
  • Property injection Pros Reflects the power of Spring dependency injection less code to write Cons Can Not mark dependency as final  unsafe code more complicated to test Construction injection Pros Can mark dependency as final which is not possible while injecting properties using property injection You don't need reflection to set the dependencies safe code easy to test Cons Coupling your class with your dependency, in fact you cannot instantiate an object without passing its dependencies from the constructor more code to write – Ishan Garg Jul 20 '21 at 05:36

0 Answers0