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

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.

主站蜘蛛池模板: 江陵县| 内江市| 广饶县| 云浮市| 汉中市| 宜阳县| 宿迁市| 高唐县| 新化县| 胶州市| 青海省| 桐梓县| 临猗县| 互助| 罗甸县| 密山市| 嘉鱼县| 双城市| 黔西县| 神木县| 旬阳县| 西畴县| 黔西| 大同市| 灌云县| 德兴市| 祥云县| 平潭县| 新泰市| 石首市| 尼玛县| 应城市| 呼和浩特市| 尤溪县| 平遥县| 大洼县| 德阳市| 惠水县| 宿州市| 皮山县| 宝鸡市|