Hi,
Is it possible to correctly initialize and destroy non-singleton beans with Spring?
I have this context:
AppBean is:Code:<beans> <bean id="commandBean" class="test.CommandBean" singleton="false" init-method="init" destroy-method="destroy"/> <bean id="appBean" class="test.AppBean"> <lookup-method name="createCommandBean" bean="commandBean"/> </bean> </beans>
CommandBean is:Code:public class AppBean { protected CommandBean createCommandBean() { return null; } public void execute() { createCommandBean(); } }
I use it with this startup code:Code:public class CommandBean { private Log log = LogFactory.getLog(getClass()); public void init() { log.info("CommandBean init : "+this); } public void destroy() { log.info("CommandBean destroy : "+this); } }
On running I see:Code:public class TestApp { public static void main(String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(new String []{"test/context.xml"}); ctx.registerShutdownHook(); ((AppBean)ctx.getBean("appBean")).execute(); ((AppBean)ctx.getBean("appBean")).execute(); ctx.close(); } }
So, there are no CommandBean.destroy calls. Is is possible to execute some code in non-singleton beans on closing context in another way?Code:INFO CollectionFactory - JDK 1.4+ collections available INFO XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [test/context.xml] INFO ClassPathXmlApplicationContext - Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext;hashCode=29315749]: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [commandBean,appBean]; root of BeanFactory hierarchy INFO ClassPathXmlApplicationContext - 2 beans defined in application context [org.springframework.context.support.ClassPathXmlApplicationContext;hashCode=29315749] INFO ClassPathXmlApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@efd552] INFO ClassPathXmlApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@18a7efd] INFO DefaultListableBeanFactory - Pre-instantiating singletons in factory [org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [commandBean,appBean]; root of BeanFactory hierarchy] INFO CommandBean - CommandBean init : test.CommandBean@1125127 INFO CommandBean - CommandBean init : test.CommandBean@18dfef8 INFO ClassPathXmlApplicationContext - Closing application context [org.springframework.context.support.ClassPathXmlApplicationContext;hashCode=29315749] INFO DefaultListableBeanFactory - Destroying singletons in {org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [commandBean,appBean]; root of BeanFactory hierarchy}


Reply With Quote