
1. Overview
In this article, we will learn to remove the bean from the context of a Spring boot application.
2. Spring boot remove bean from context
Sometimes, you need to remove a bean from the application context.
You can either remove the bean definition or the bean alone. A BeanDefinition
describes a bean instance, which has property values, constructor argument values, and further information.
For example, the following is a bean definition from the configuration XML.
<beans> ... <bean id="subject" class="com.tedblob.beans.Student" factory-method="createInstance"> </bean> ... </beans>
An Application context uses the bean definitions specified in the configuration metadata such as XML configuration, annotation based configuration or Java configuration to instantiate, manage the Spring beans.
To learn about bean instantiation, refer to this article.
3. Remove bean using Spring BeanDefinitionRegistry
The BeanDefinitionRegistry
is the only interface in Spring’s bean factory packages that encapsulates the registration of bean definitions. You can use this registry to remove or register the beans dynamically.
It allows you to remove bean definition and destroys all container references on that bean.
To register a new bean definition, use registerBeanDefinition
.
registry.registerBeanDefinition(beanId, newBeanObj);
To remove an existing bean definition, use removeBeanDefinition
.
registry.removeBeanDefinition(beanId);
You can remove and add a new bean definition at runtime by using the following code:
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory(); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory; registry.removeBeanDefinition(beanId); registry.registerBeanDefinition(beanId, newBeanObj);
4. Remove singleton bean from context
DefaultListableBeanFactory
supports this through the registerSingleton
and destroySingleton
methods, as defined by the org.springframework.beans.factory.config.ConfigurableBeanFactory
interface.
If you just need to remove the singleton bean then use destroySingleton
:
((DefaultListableBeanFactory) beanFactory).destroySingleton("myBean");
The bean definitions provide information on how to create a specific bean for the BeanFactory
. However, you can also allow registering existing bean objects that are created outside the factory (by custom code).
For example, the following code registers the CustomBean
object using the registerSingleton
method. You can see this article to know more about the registerSingleton
method.
((SingletonBeanRegistry) beanFactory).registerSingleton("myBean", myBeanInstance);
5. Conclusion
To sum up, we have learned to remove bean from the BeanFactory in a Spring boot application. You can find code samples of this article in our GitHub repository.