Register Spring Beans to BeanFactory using registerSingleton

Spring’s strength lies on its core framework’s Inversion Of Control (IOC) and how the beans are instantiated and managed by the IOC container. All the beans in the spring’s IOC containers are managed as the singleton beans by default for the efficient and good performance. As a good practice, you should never create instance for an object in the Spring application and every class has to be configured as beans in the application context. However, in few scenarios, you have to register a bean to the IOC container at run time which means outside the IOC container.

If you register a bean outside the container, then you have to code it separately for any callback methods to be invoked. The default mechanism of callbacks won’t be invoked for the beans registered outside the IOC. You need to create BeanDefinition object for adding the callback functionality.

Look at the below code snippet for registerSingleton example to register SimpleBean class to the IOC container.

1. Add the Required JAR Files

Look at the below picture for the list of required JAR files to run this example.


2. Create Spring Application Context and Sample Bean


import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;

public class SpringBeans {
	public static void main (String args[]){
		ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("file:/home/krishna/git/SpringTestFramework/Spring TestFramework/WebContent/WEB-INF/dispatcher-servlet.xml");
		ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
		beanFactory.registerSingleton("simplebean", new SimpleBean());
		SimpleBean bean = (SimpleBean)applicationContext.getBean("simplebean");


public class SimpleBean {
	public void print(){
		System.out.println("Register Outside Container");

3. Create Spring Configuration File

A simple spring xml configuration file for this example.

<beans xmlns=""

	<context:component-scan base-package=""/>

        <!--Bean definitions goes here -->

I hope this example would help you to understand how to add a bean to the bean factory. There are many other ways you can add the beans to the bean factory. You can try yourself with different approaches.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!