- 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.
- JavaScript從入門到精通(微視頻精編版)
- 數(shù)據(jù)庫原理及應(yīng)用(Access版)第3版
- Android 9 Development Cookbook(Third Edition)
- Mastering matplotlib
- Java:Data Science Made Easy
- 零基礎(chǔ)學(xué)Java程序設(shè)計(jì)
- Flux Architecture
- 學(xué)習(xí)正則表達(dá)式
- 詳解MATLAB圖形繪制技術(shù)
- Visual Studio Code 權(quán)威指南
- Oracle數(shù)據(jù)庫編程經(jīng)典300例
- Spring Web Services 2 Cookbook
- Azure for Architects
- 多接入邊緣計(jì)算實(shí)戰(zhàn)
- GitHub Essentials