
Spring μμ μΌλ°μ μΈ Bean μ lifecycle μ μμ κ°μ νμμ΄λ€. μ΄λ, Bean Lifecycle Method λ₯Ό μ¬μ©νμ¬ Bean μ΄ μμ±λκ³ μλ©Έλλ μμ μ μΆκ°μ μΈ μμ μ μννλλ‘ customize ν μ μλ€.
νΉμ μμ (initialize λλ destory)μ μ€νλλλ‘ κ±Έμ΄ λμ Hook μ΄λΌκ³ λΆλ₯Ό μλ μμΌλ©°, νΉμ μ΄λ²€νΈ(initialize λλ destory) λ°μ μμ μλμΌλ‘ νΈμΆλλ method μΈ μ μμ Callback μ΄λΌκ³ λΆλ₯΄κΈ°λ νλ€.
Bean Initialization μμ μμλ custom business logic methods λ₯Ό νΈμΆνκ±°λ, DB λ±μ resource κ΄λ ¨ μ€μ μ μ€λΉνκ² ν μ μλ€. @PostConstruct annotation μ μ¬μ©νμ¬ Lifecycle Callback μ λ§λ€ μ μλ€.
λ§μ°¬κ°μ§λ‘, Bean Destruction μμ μμλ business logic μ νΈμΆνκ±°λ resource κ΄λ ¨ μμ
λ€μ μ 리νκ² ν μ μκ³ , @PreDestroy annotation μ μ¬μ©νμ¬ Lifecycle Hook μ λ§λ€ μ μλ€.
Bean Lifecycle Methods - Test
μ°μ FootballCoach Bean μ λν Bean scope λ₯Ό λ€μ Default λ‘ λ°κΎΈμ΄μ£Όκ³ , custom init method μ destroy method λ₯Ό ν΄λΉ Bean μ λ€μκ³Ό κ°μ΄ μΆκ°ν΄μ£Όμ.
@Component
public class FootballCoach implements Coach {
...
// define custom init method
@PostConstruct
public void doMyStartupStuff() {
System.out.println("In doMyStartupStuff(): " + getClass().getSimpleName());
}
// define custom destroy method
@PreDestroy
public void doMyCleanupStuff() {
System.out.println("In doMyCleanupStuff(): " + getClass().getSimpleName());
}
...
}μ΄ν Application μ μ€ννκ³ λ°λ‘ μ’ λ£μν€κ² λλ©΄ console μμ λ€μκ³Ό κ°μ κ²°κ³Όλ₯Ό νμΈν μ μλ€.

λ¨Όμ , FootballCoach μ λν Bean instantiated κ° λ μ΄νμ, μμ±ν΄μ€ init method κ° μ€νλ κ²μ μ μ μμΌλ©°, Application μ μ’
λ£νκΈ° μ§μ μ, μμ±ν΄μ€ destroy method κ° μ€νλ κ²μ μ μ μλ€.
! Special Note for Prototype Scope
Bean μ scope λ₯Ό Prototype μΌλ‘ μ€μ ν΄λμλ€λ©΄ μ¬κΈ°μμ μμ±λ κ²μ²λΌ, Bean instantiated λ€μμ λμ΄μ Spring Container κ° κ΄λ¦¬νμ§ μλλ€. μ€μ λ‘ Prototype μΌλ‘ scope λ₯Ό μ§μ νκ³ test ν΄λ³΄λ©΄,

κ³Ό κ°μ΄ Bean μ μ΄κΈ°νν μ΄νμ init method λ μ μμ μΌλ‘ μ€νμ΄ λμμ§λ§, Application μ μ’ λ£νμμλ destroy method λ μ€νλμ§ μμμμ μ μ μλ€. κ·Έλ λ€λ©΄ Prototype μΌλ‘ scope κ° μ§μ λ Bean λ€μ μ μ΄λ μ΄κΈ°ν μ΄νμ λκ° κ΄λ¦¬νλ κ²μΌκΉ?
λ°λ‘ κ°λ°μμκ² κ·Έ κΆνκ³Ό μ± μμ΄ μλ€. λ§μ½ init method μμ DB λ±κ³Ό κ°μ resource λ€μ startup νλ€λ©΄, λ°λμ κ°λ°μλ μ§μ ν΄λΉ resource λ€μ release νκ±°λ cleanup μμΌμΌ νλ€. μ¦, κ°λ°μκ° μ§μ destory logic μ μμ±νκ±°λ ν΄λΉ κΈ°λ₯μ μννλ method λ₯Ό call ν΄μΌ νλ κ²μ΄λ€.