I am reading the Pro Spring 2.5 book and in chapter 4 they talk about life cycle callbacks. How is Spring able to notify when an instance is destroyed (after what I read it is only available on singletons)? What mechanism is used?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No magic here, destroy callbacks are called when the
BeanFactory/ApplicationContextis destroyed (close()method is called). In desktop applications this has to be done manually, in servlet environment the same mechanism that was used to start the application context (typicallyContextLoaderListener) handled destroying for you.Two notes:
destroying is important for objects requiring explicit clean-up like database connection pools (
DataSource) or threads.Beans are destroyed in the opposite order compared to creation order. This is understandable: when bean
Adepends onB,Bhas to be created first. When beanAis destroyed,Bhas to be destroyed afterwards, otherwiseAwould not be able to access its dependencies during destroy phase.Also Spring allows you to automatically register shutdown hook to handle shutdown automatically. I wouldn’t advice that, but just for the record: