关于spring:Why-using-constructor-based-dependency-injection-Spring

2次阅读

共计 1930 个字符,预计需要花费 5 分钟才能阅读完成。

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

正文完
 0