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") 와 같이 μž‘μ„±ν•˜λ©΄ λœλ‹€.