- 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.
- GAE編程指南
- JavaScript全程指南
- C語(yǔ)言程序設(shè)計(jì)案例教程(第2版)
- PHP 7底層設(shè)計(jì)與源碼實(shí)現(xiàn)
- 信息可視化的藝術(shù):信息可視化在英國(guó)
- 零基礎(chǔ)學(xué)Java(第4版)
- 基于Struts、Hibernate、Spring架構(gòu)的Web應(yīng)用開發(fā)
- 從零開始學(xué)Python網(wǎng)絡(luò)爬蟲
- C++編程兵書
- 創(chuàng)意UI:Photoshop玩轉(zhuǎn)APP設(shè)計(jì)
- JavaWeb從入門到精通(視頻實(shí)戰(zhàn)版)
- Go語(yǔ)言從入門到進(jìn)階實(shí)戰(zhàn)(視頻教學(xué)版)
- 匯編語(yǔ)言程序設(shè)計(jì)教程
- HTML 5與CSS 3權(quán)威指南(第4版·下冊(cè))
- Java Web應(yīng)用設(shè)計(jì)及實(shí)戰(zhàn)