Spring Framework - BeanDefinitionRegistryPostProcessor Examples

Spring Framework 

Implementation of BeanDefinitionRegistryPostProcessor can be used to register objects as Spring beans programmatically.

package com.logicbig.example;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class BeanDefinitionRegistryPostProcessorExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(MyConfig.class);

MyBean bean = (MyBean) context.getBean("myBeanName");

public static class MyConfig {
MyConfigBean myConfigBean () {
return new MyConfigBean();

private static class MyConfigBean
implements BeanDefinitionRegistryPostProcessor {

public void postProcessBeanDefinitionRegistry (BeanDefinitionRegistry registry)
throws BeansException {

GenericBeanDefinition bd = new GenericBeanDefinition();
bd.getPropertyValues().add("strProp", "my string property");
registry.registerBeanDefinition("myBeanName", bd);

public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory)
throws BeansException {
//no op

private static class MyBean {
private String strProp;

public void setStrProp (String strProp) {
this.strProp = strProp;

public void doSomething () {
System.out.println("from MyBean: " + strProp);


from MyBean:  my string property
WARNING: Cannot enhance @Configuration bean definition 'beanDefinitionRegistryPostProcessorExample.MyConfig' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
Original Post

See Also