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
SpringBeans.java
package javabeat.net; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; 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"); bean.print(); applicationContext.close(); } }
SimpleBean.java
package javabeat.net; 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="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <context:component-scan base-package="javabeat.net"/> <!--Bean definitions goes here --> </beans>
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.