How to create spring beans dynamically?

Spring beans can be created dynamically using the following steps.

  1. Get the appropriate bean factory from application context.
  2. Get the bean definition registry from bean factory.
  3. Create your bean definition.
  4. Register the bean in the registry. 

Example Code:

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;

public class DynamicBeanTest {
    static ApplicationContext appContext = null;

    private void createDynamicBean() {
        AutowireCapableBeanFactory factory = null;
        appContext = new ClassPathXmlApplicationContext("spring-beans.xml");
        factory = appContext.getAutowireCapableBeanFactory();
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        registry.registerBeanDefinition("sampleBean", beanDefinition);
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

    public static void main(String[] args) {
        DynamicBeanTest dynamicBeanTest = new DynamicBeanTest();
        SampleBean sampleBean = getBean(SampleBean.class);

    private static <T> T getBean(Class <? extends T> type) {
        String beanName = type.getSimpleName();
        beanName = beanName.substring(0, 1).toLowerCase()
                + beanName.substring(1);
        return (T) appContext.getBean(beanName);

class SampleBean {

    public void method1() {

Note: Ensure that spring-beans.xml is present in classpath before executing the above code.

Now you have invented how to define spring beans dynamically.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: