Setter Injection 은 Setter λ₯Ό μ΄μš©ν•˜λŠ” Injection 방식 쀑 ν•˜λ‚˜μ΄λ‹€.

Setter λ₯Ό μ΄μš©ν•˜λŠ” 방식은 κ°„λ‹¨ν•˜λ‹€. class 에 Injection 을 λ‹΄λ‹Ήν•˜λŠ” method λ₯Ό ν•˜λ‚˜ μƒμ„±ν•˜κ³ , @Autowired annotation 을 ν†΅ν•˜μ—¬ μ›ν•˜λŠ” Bean object λ₯Ό Inject ν•΄μ£Όλ©΄ λœλ‹€. μ΄λ²ˆμ—λŠ” λ°”λ‘œ code λ₯Ό μž‘μ„±ν•΄λ³΄μž.

Setter Injection - Code
// define a setter for dependency injection  
@Autowired  
public void setCoach(Coach theCoach) {  
    myCoach = theCoach;  
}

사싀, Setter Injection 을 μ‚¬μš©ν•  λ•Œ method 의 이름은 상관이 μ—†λ‹€. λ‹¨μˆœνžˆ Injection 을 μˆ˜ν–‰ν•˜λŠ” method κ·Έ 이상 κ·Έ μ΄ν•˜λ„ μ•„λ‹ˆκΈ° λ•Œλ¬Έμ— 말이 setter 이지 사싀상 일반적인 method 라 봐도 λ¬΄λ°©ν•˜λ‹€. 단지 Injection 을 μˆ˜ν–‰ν•˜λŠ” κΈ°λŠ₯을 κ°€μ§€κ³  μžˆμ–΄μ„œ λͺ…μ‹œμ μœΌλ‘œ Setter λΌλŠ” 이름을 μ£ΌλŠ” 것 뿐이닀.

Constructor vs. Setter Injection

그럼 μ–΄λŠ 상황에 μ–΄λ–€ Injection 을 μ‚¬μš©ν•΄μ•Ό ν•˜λŠ” 걸까?

Constructor Injection 은 constructor λ₯Ό μ΄μš©ν•˜λŠ” λ°©μ‹μœΌλ‘œ, object 생성 μ‹œμ μ— λ°˜λ“œμ‹œ μ„€μ •λ˜λ―€λ‘œ ν•„μˆ˜μ μΈ dependency λ₯Ό μ²˜λ¦¬ν•  λ•Œ μ ν•©ν•˜λ‹€.

λ°˜λŒ€λ‘œ Setter Injection 은 dependency λ₯Ό μ„ νƒμ μœΌλ‘œ μ„€μ •ν•  수 μžˆμœΌλ―€λ‘œ optional dependency λ₯Ό μ²˜λ¦¬ν•  λ•Œ μ ν•©ν•˜λ‹€.