Why using constructor based dependency injection | Spring

Posted Bran.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Why using constructor based dependency injection | Spring相关的知识,希望对你有一定的参考价值。

Introduction

When I am diving into spring framework, I noticed different ways to initialize dependency injection.

The normal way is field based dependency injection, the most easy-read and simple way by merely add the annotation @Autowired

@Controller
public class testController {
    @Autowired
    priviate testService testService;
}

The second way is called setter based dependency injection

@Controller
public class testController {
    priviate testService testService;
    @Autowired
    public void testService(testService testService) {
      this.testService = testService;
  }
}

I seldom used this kind of way, explanation from spring doc.

The Spring team generally advocates setter injection, because large numbers of constructor arguments can get unwieldy, especially when properties are optional. Setter methods also make objects of that class amenable to reconfiguration or re-injection later. Management through JMX MBeans is a compelling use case.

Some purists favor constructor-based injection. Supplying all object dependencies means that the object is always returned to client (calling) code in a totally initialized state. The disadvantage is that the object becomes less amenable to reconfiguration and re-injection.

This way is the common way that I am using now --- constructer based dependency injection, combining it with Lombok is easier to read.

@Service
@Transactional
public class StudentService {

    private final StudentRepository studentRepo;

    public StudentService(StudentRepository studentRepo) {
        this.studentRepo=studentRepo;
    }
    // complete service code using studentRepo
}

why

answer from here

  • the dependencies are clearly identified. There is no way to forget one when testing, or instantiating the object in any other circumstance (like creating the bean instance explicitly in a config class)
  • the dependencies can be final, which helps with robustness and thread-safety
  • you don\'t need reflection to set the dependencies. InjectMocks is still usable, but not necessary. You can just create mocks by yourself and inject them by simply calling the constructor

Reference

1.An introduction to three different way to dependency injection

2.An inspiring way to combine constructor based DI with Lombok

3.a good article for DI

4.A closer look into DI

以上是关于Why using constructor based dependency injection | Spring的主要内容,如果未能解决你的问题,请参考以下文章

Why Use the Widget Factory?

Why does OpenCV use BGR color format ?

Why SignalR does not use WebSockets?

Why I don't want use JPA anymore

why do we need, what advantages to use mongoose

SQL Server 2019 的亮点总结 Why use SQL Server