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

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.

主站蜘蛛池模板: 榆树市| 繁峙县| 罗田县| 苍南县| 淳化县| 庆安县| 安阳县| 新丰县| 肇庆市| 东阿县| 内丘县| 盐源县| 德钦县| 和田市| 和硕县| 台北县| 太保市| 麻栗坡县| 长阳| 那曲县| 南澳县| 岳西县| 凌海市| 巴楚县| 通江县| 萨嘎县| 紫金县| 鸡东县| 古浪县| 琼海市| 肥西县| SHOW| 安顺市| 玉龙| 淮北市| 碌曲县| 泰顺县| 合川市| 旬邑县| 乐亭县| 金阳县|