简体   繁体   中英

how to do runtime bean deployement and destroy a bean in spring ioc container?

I have an application which is having a ClassPathXMLApplicationContext which has loaded some beans from spring xml files. I want to add a bean at runtime. So i created another instance of ClassPathXMLApplicationContext which reads the new bean definitions from new xml files. Now i have two appContexts.

My Question is: how do i copy the beans from the new context to the old context? is it necessary to copy? cant i just merge these two contexts? is there an api for merging?

Later i want to undeploy the bean a runtime. I also want classloader to unload the bean class when i delete the bean.

How to delete a bean from an ApplicationContext and also unload the bean class.

Thanks, Regards, Vimal

You don't need second instance of ClassPathXMLAplicationContext. I think this will help you :

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
Product myProduct = (Product) context.getBean("Batery");
//when you want to change the bean with another
myProduct = (Product) context.getBean("CD-RW");

In the XML file you need two beans where "Batery" could initialize with what you want, but "CD-RW" can't be initialized with constructor. Here is an example with setter initialize :

<bean id="Batery" class="com.seller.springtest1.Battery">
    <property name="name" value="AAA" />
    <property name="price" value="2.5" />
</bean>

<bean id="CD-RW" class="com.seller.springtest1.Disc">
    <property name="name" value="CD-RW" />
    <property name="price" value="1.5" />
</bean>

I don't get the aquestion about deletion(it's garbage collector function) if you have special needs(when you retained the myProduct reference) you could do myProduct = null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM