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.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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();
        beanDefinition.setBeanClass(SampleBean.class);
        beanDefinition.setAutowireCandidate(true);
        registry.registerBeanDefinition("sampleBean", beanDefinition);
        factory.autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
    }

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

    @SuppressWarnings("unchecked")
    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() {
        System.out.println("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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: