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 ν•΄μ•Ό ν•˜λŠ” 것이닀.