In constructor injection, the dependencies needed for the class are provided as arguments to the constructor. This practice follows the OOP concept, which instructs to use constructors to create object instances.
Note: In the newer versions of spring-boot, adding an
@Autowired
annotation to the constructor is optional if the class has only one constructor. This functionality was not provided before Spring 4.3.
package com.greglturnquist.hackingspringboot.reactive;import reactor.core.publisher.Flux;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ServerController {private final KitchenService kitchen;public ServerController(KitchenService kitchen) {this.kitchen = kitchen;}}
Line 7: We define a public class named ServerController
.
Line 8: We define an object named kitchen
of the class KitchenService
.
Line 9: We are defining a parameterized constructor. Then we provide KitchenService
to this controller via constructor injection. Spring will seek out an instance of this service when the app starts and feed it automatically to the constructor.
package com.greglturnquist.hackingspringboot.reactive;import reactor.core.publisher.Flux;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ServerController {private final KitchenService kitchen;private final BathroomService bathroom;public ServerController(KitchenService kitchen) {this.kitchen = kitchen;}@Autowiredpublic ServerController(KitchenService kitchen, BathroomService bathroom) {this.kitchen = kitchen;this.bathroom = bathroom;}}
Line 7: We define a public class named ServerController
.
Line 8: We define an object named kitchen
of the class KitchenService
.
Line 9: We define an object named bathroom
of the class BathroomService
.
Line 11: We define a constructor with one parameter. Since @Autowired
is not added to this constructor, Spring will not look for this constructor to inject dependencies.
Line 15: We explicitly add the @Autowired
annotation so that Spring will know this is the constructor to use to inject the dependencies.
Line 16: We define a constructor with two parameters. The classes, KitchenService
and BathroomService
, are provided to this controller via constructor injection. Spring will seek out an instance of these services when the app starts and feed them automatically to this constructor.
Free Resources