Programmatically registering beans by implementing BeanDefinitionRegistryPostProcessor

package com.logicbig.example;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory)
throws BeansException {
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(MyBean.class);
bd.getPropertyValues().add("strProp", "my string property");
((DefaultListableBeanFactory) beanFactory)
.registerBeanDefinition("myBeanName", bd);
}
}

package com.logicbig.example;
public class MyBean {
private String strProp;
public void setStrProp(String strProp) {
this.strProp = strProp;
}
public void doSomething() {
System.out.println("from MyBean: " + strProp);
}
}

package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public static MyBeanFactoryPostProcessor myConfigBean() {
return new MyBeanFactoryPostProcessor();
}
}

package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BeanFactoryPostProcessorExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
bean.doSomething();
}
}
Output
from MyBean: my string property
Original Post