Spring μμ νΉμ class λ₯Ό Bean μΌλ‘ λ±λ‘νκΈ° μνμ¬λ ν΄λΉ class μ @Component annotation μ μ¬μ©νμλ€.
μ΄ λ°©λ² λ§κ³ λ @Configuration annotation μ μ§μ ν class λ₯Ό λ°λ‘ λ§λ€κ³ , ν΄λΉ class μμμ @Bean annotation μ μ¬μ©ν method λ₯Ό λ§λ€μ΄μ Bean instatiation μ μνν μ μλ€. μλ‘μ΄ Class SwimCoach λ₯Ό Bean μΌλ‘ λ±λ‘νκΈ° μν΄μλ μλμ κ°μ΄ μ¬μ©νλ©΄ λλ€.
@Configuration
public class SportConfig {
@Bean
public Coach swimCoach() {
return new SwimCoach();
}
}κ·Έλ¬λ μ΄λ° μλ¬Έμ κ°μ§ μ μλ€. κ·Έλ₯ new keyword λ₯Ό μ¬μ©νλ©΄ λλ κ² μλκ°? κ·Έλ₯ λ¨μνκ² class μ @Component annotation λΆμ΄λ κ²μ΄ ν¨μ¬ κ°λ¨ν μμ
μλκ°?
μ°μ new keyword μ λνμ¬λ, Spring Container λ‘ Bean μ κ΄λ¦¬νλ κ²μ ν¨μ¬ λ λ§μ μ΄μ κ³Ό νΈλ¦¬ν¨, ν¨μ¨μ±μ΄ μ‘΄μ¬νλ€λ κ²μ λ°λ°μΌλ‘ λ€ μ μλ€. λ¨μν new keyword λ₯Ό ν΅νμ¬ Bean object μμ±νλ©΄, Bean μ λν λͺ¨λ lifecycle μ κ°λ°μκ° μ§μ κ΄λ¦¬ν΄μΌ νκΈ° λλ¬Έμ μ΄λ €μμ΄ μ‘΄μ¬νλ€.
λ€μμΌλ‘λ, λ¨μν @Component annotation μ μΆκ°ν μ μλ μν©μ΄ μ‘΄μ¬νλ€. λ§μ½ third-part μ class λ₯Ό μ¬μ©νκ³ μΆμ λ, ν΄λΉ class λ read-only μΈ κ²½μ°κ° λ€λ°μ¬μΌ κ²μ΄λ€. read-only μΈ νμΌμ write λ₯Ό νλ κ²μ μ¬μ€μ λΆκ°λ₯νκΈ° λλ¬Έμ, @Configuration μ μ¬μ©ν class λ₯Ό μΆκ°μ μΌλ‘ μμ±νμ¬ ν΄λΉ class μμ third-party class μ λν Bean μ μμ±ν μ μλ€.
μ΄ν Application μ Controller λ λ€λ₯Έ service μ DI λ₯Ό μννλ©΄, third-party μ λν class λ Bean μΌλ‘ λ±λ‘νμ¬ μ¬μ©ν μ μκ² λλ κ²μ΄λ€.
Bean ID
Bean ID λ Spring Container μμ Bean λ€μ ꡬλ³ν μ μλ κ³ μ ν μ΄λ¦μ΄λ€.
κΈ°λ³Έμ μΌλ‘ Bean ID λ ν΄λΉ class μ΄λ¦μ 첫 λ²μ§Έ κΈμλ₯Ό μλ¬Έμλ‘ λ°κΎΌ κ²μ μ¬μ©νλ€. λ°λΌμ μλμ κ°μ΄ Qualifier λ₯Ό ν΅νμ¬ Injection μ μνν λ swimCoach λ₯Ό μ¬μ©ν κ±Έ μ μ μλ€.
// define a constructor for dependency injection
@Autowired
public DemoController(@Qualifier("swimCoach") Coach theCoach) {
System.out.println("In constructor: " + getClass().getSimpleName());
myCoach = theCoach;
}Bean ID λ₯Ό μ§μ configure ν μ μλλ°, λ¨μνκ² @Bean annotation μ μ¬μ©νλ κ²μ΄ μλλΌ @Bean("aquatic") μ κ°μ΄ Bean ID λ₯Ό μ§μ μ§μ νμ¬ μ¬μ©ν μ μλ€. ν΄λΉ Bean μ Injection ν λλ @Qualifier("aquatic") μ κ°μ΄ μμ±νλ©΄ λλ€.