官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 中西区| 乌鲁木齐县| 临颍县| 都昌县| 济源市| 涟水县| 德兴市| 陵水| 乾安县| 息烽县| 天镇县| 武定县| 延吉市| 荔浦县| 瑞金市| 从江县| 东宁县| 吐鲁番市| 黄冈市| 瓮安县| 富民县| 曲周县| 肇州县| 武功县| 鱼台县| 清徐县| 惠安县| 高阳县| 宜丰县| 闵行区| 西林县| 瓦房店市| 从化市| 年辖:市辖区| 土默特左旗| 涟水县| 舒兰市| 玉田县| 贡嘎县| 凌海市| 金川县|