- Kotlin Blueprints
- Ashish Belagali Hardik Trivedi Akshay Chordiya
- 282字
- 2021-07-02 21:50:11
Constructor injection
Dependency injection is a key feature of Spring (and Spring Boot). It reduces the coupling or in other words, makes the classes less dependent on one another. This increases the possibility to reuse them and also helps to test the app.
Spring provides three ways to inject the dependencies—Field, Constructor, and Setter injection:
- In field injection, you just declare the field and add an annotation on top of the field declaration. Although highly readable, this practice could go higher as the fields grow and also increases the dependence on a specific Spring container, thereby making testing difficult. Field injection is therefore not recommended.
- Constructor injection is about adding a constructor that initializes the fields and hence the injection annotations appear over the constructor. This is the preferred mechanism for injecting mandatory fields.
- Setter injection is about annotating the setter method. This is the preferred mechanism for injecting non-mandatory fields, typically to override default settings.
Between field injection and constructor injection, most Java developers use field injection (with all its associated problems). This is because constructor injection in Java has a lot of boilerplate code that makes it look bloated:
@RestController
@RequestMapping("/message")
public class MessageController {
private MessageRepository repository;
public MessageController(MessageRepository repository) {
this.repository = repository;
}
}
In Kotlin, constructor injection looks clean, light, and concise; and the boilerplate is all gone. Here is the Kotlin equivalent of the preceding code:
@RestController
@RequestMapping("/message")
class MessageController(val repository: MessageRepository) {
}
So, now there is more reason for developers to say goodbye to the field injection.
Since Spring Framework 4.3 there is no need to use the @Autowire annotation in the case of a single constructor class.
- 一步一步學Spring Boot 2:微服務項目實戰
- 數據結構習題精解(C語言實現+微課視頻)
- Learning FuelPHP for Effective PHP Development
- C#應用程序設計教程
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- ArcGIS for Desktop Cookbook
- Processing創意編程指南
- 計算機應用基礎項目化教程
- OpenCV Android Programming By Example
- Mastering PowerCLI
- 計算機程序的構造和解釋(JavaScript版)
- Three.js Essentials
- Mastering Responsive Web Design
- Learning Ext JS(Fourth Edition)
- Mastering Chef Provisioning