Search code examples
springjavabeansdestroy

spring destroy bean manually instead of ctx.close()


is it possible to tell the container of spring to destroy a specific bean (prototype) in order to save up memory?

I dont want to user ctx.close() in order to see this bean destroyed, but rather on runtime.


Solution

  • If I understand you correctly you want to remove a bean that was defined in the ctx at runtime. You can use BeanDefinitionRegistry which has the method removeBean() that takes a bean name as the parameter.

    BeanDefinitionRegistry factory = 
       (BeanDefinitionRegistry) applicationCtx.getAutowireCapableBeanFactory();
    

    Then

    ((DefaultListableBeanFactory) beanFactory).destroySingleton("myBean");
    

    EDIT

    reference http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/beans/factory/support/BeanDefinitionRegistry.html#removeBeanDefinition%28java.lang.String%29