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 λ₯Ό μ²λ¦¬ν λ μ ν©νλ€.