Constructor Injection μ μμμ μ€λͺ νλλ‘, constructor λ₯Ό μ΄μ©νλ Injection λ°©μμ΄λ€.

μ°μ μμ μλ리μ€λ₯Ό μ μ©ν΄λ³΄κΈ°λ‘ νμ. μ°μ /dailyworkout endpoint μ μ κ·Όνλ©΄, DemoController λΌλ controller λ₯Ό ν΅νμ¬ Coach object μ getDailyWorkout method λ₯Ό μ€ννλλ‘ νλ λ°©μμ΄λ€.

Coach object λ Dependency Injection μ μνμ¬ Interface λ‘ λ§λ€κ³ , μ΄λ₯Ό κ°κ°μ class κ° implements νλ μμΌλ‘ ꡬμ±νλ©΄ DIP(Dependency Inversion Principle) λ λ§μ‘±ν κ²μ΄λ€.
Constructor Injection - Code
@RestController
public class DemoController {
// define a private field for the dependency
private Coach myCoach;
// define a constructor for dependency injection
@Autowired
public DemoController(Coach theCoach) {
myCoach = theCoach;
}
@GetMapping("/dailyworkout")
public String getDailyWorkout() {
return myCoach.getDailyWorkout();
}
}μ°μ FootballCoach class λ§μ @Component annotation μ ν΅νμ¬ Spring Bean μΌλ‘ μ€μ νμ¬ Spring Container μ μ μ₯νλ€. μ΄ν Controller μμλ Autowiring μ ν΅νμ¬ λ€μ΄μ¨ FootballCoach κ° Controller μ constructor μ injection λλ€.
μ¦, Constructor Injection μ΄ μνλ κ²μ΄λ€.
Constructor Injection - Behind the Scenes
DI(Dependency Injection) μ ν΅νμ¬ object κ° injection λ κ²μ μκ² λ€. νμ§λ§ μμ£Ό μ μκ³ μλ―μ΄, Java μμλ λ¨μν class type μ field λ₯Ό μ μΈνλ€κ³ ν΄μ ν΄λΉ class μ object κ° μκΈ°λ κ²μ μλλ€. μ½λμμμλ theCoach λ DemoController λ¨μν μ μΈλ§ νμ λΏ μ€μ object λ₯Ό μμ±νλ λΆλΆμ 보μ΄μ§ μλλ€.
μ΄λ° μν μ λ΄λΆμ μΌλ‘ μννλ κ²μ΄ λ°λ‘ Spring IoC Container, μμμ μΈκΈν Spring Container μ΄λ€. Spring Container λ Spring Container λΆλΆμμ μΈκΈν κ²μ²λΌ object λ₯Ό λ§λ€κ³ , dependency λ₯Ό injection νλ μν μ μννλ€. λ°λΌμ Spring IoC Container λ λ΄λΆμ μΌλ‘ μλμ μ½λλ₯Ό μννλ κ²μ΄λ€.
Coach theCoach = new FootballCoach();
DemoController demoController = new DemoController(theCoach);λ€μ νλ² μ€λͺ
νλ©΄, 첫 λ²μ§Έ codeline μμλ Spring Bean μΌλ‘ λ±λ‘λ FootballCoach class μ λν μ€μ theCoach λΌλ Coach type μ object λ₯Ό μ μΈν κ²μ΄κ³ , λ λ²μ§Έ codeline μμλ theCoach object λ₯Ό injection νμ¬ Constructor λ₯Ό ν΅ν initialization, μ¦ Constructor Injection μ μννμλ€.
νμ§λ§, μ΄λ° μκ°μ λ μ¬λ¦΄ μ μλ€.
μλ, κ·Έλ₯ βnewβ keyword λ₯Ό μ¬μ©ν΄μ object λ₯Ό μμ±νλ©΄ λλκ±° μλμΌ? μ 볡μ‘νκ² Spring Container μκ² μ΄ μμ μ μννκ² νλκ±°μΌ.
Why using Spring IoC Container
λ¬Όλ‘ , μμ application μ λνμ¬ Spring Container λ₯Ό ν΅νμ¬ IoC λ DI μ μ΄μ μ μ λλΌμ§ λͺ»ν κ²μ΄λ€. νμ§λ§ Spring μ 볡μ‘ν application μ λ¬Όλ‘ , κΈ°μ , real-time / real-world application μ λμμΌλ‘ νλ€. λν Database μ λν μ κ·Ό, Transacations, REST APIs, Web MVC, Spring Security λ±μμ μμ£Ό ν¨μ¨μ μΌλ‘ μ¬μ©λλ€.
λΌμ μ΄λ‘ μ»λ κ²μ μμΌλ‘ λ λ껴보λλ‘ νμ.