$show=/label

BeanDefinitionRegistryPostProcessor - Spring Boot Bean Registration Runtime Example

SHARE:

A quick guide to how to register a bean in spring with beandefinitionregistrypostprocessor interface dynamically at runtime. Created an example to get bean at runtime and possible exceptions.

1. Introduction


In this tutorial, You'll learn about BeanDefinitionRegistryPostProcessor interface in Spring and Spring Boot.

BeanDefinitionRegistryPostProcessor interface has one abstract method "void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException".

This is mainly useful if you have any third-party libraries which are not spring beans. So, these beans can be registered dynamically at runtime based on your need.

BeanDefinitionRegistryPostProcessor is also one of the interfaces to register the beans at runtime without using @Bean or @Component annotations in the program.

BeanDefinitionRegistryPostProcessor - Spring Boot Bean Registration Runtime Example


From API:

Extension to the standard BeanFactoryPostProcessor SPI, allowing for the registration of further bean definitions before regular BeanFactoryPostProcessor detection kicks in. In particular, BeanDefinitionRegistryPostProcessor may register further bean definitions which in turn define BeanFactoryPostProcessor instances.

Spring Boot BeanDefinitionRegistryPostProcessor


So, Any classes that implement the BeanDefinitionRegistryPostProcessor interface will be executed before the start BeanFactoryPostProcessor registration.


2. Spring BeanDefinitionRegistryPostProcessor Example


First, Created a bean class "MyNewBean" without any @Bean or @Componet annotation.

Second, I created a class with the name MyBeanRegistration that implements BeanDefinitionRegistryPostProcessor. And also you need to override the abstract method postProcessBeanDefinitionRegistry().

Register the bean with "GenericBeanDefinition" instnace using setBeanClass(MyNewBean.class) method.

Third step is to register the MyBeanRegistration class with Spring boot. So, created another class MyCofig that is registered with Spring and registers the beans configured in it.

Finally, get the bean from the application context from the main method and call doSomeThing() method.


package com.javaprogramto.springboot.SpringBootCofigurations;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

class MyNewBean {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void doSomething() {
        System.out.println("MyNewBean name  " + name);
    }
}

class MyBeanRegistration
        implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
            throws BeansException {

        GenericBeanDefinition bd = new GenericBeanDefinition();
        bd.setBeanClass(MyNewBean.class);
        bd.getPropertyValues().add("name", "MycustomBean");

        registry.registerBeanDefinition("myNewBean", bd);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
            throws BeansException {

    }
}

@Configuration
class MyConfig {
    @Bean
    MyBeanRegistration myConfigBean() {
       return new MyBeanRegistration();
   }
}

public class BeanDefinitionRegistryPostProcessorExample {

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

        MyNewBean bean = (MyNewBean) context.getBean("myNewBean");
        bean.doSomething();
    }

}


Output:


13:12:43.593 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'

13:12:43.594 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'

13:12:43.596 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'

13:12:43.597 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'

13:12:43.604 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myNewBean'
MyNewBean name  MycustomBean

3. BeanDefinitionRegistryPostProcessor Runtime Errors

Error 1:

com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample

12:37:06.914 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@9e89d68

12:37:06.935 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'

12:37:06.989 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myConfigBean'

12:37:06.992 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beanDefinitionRegistryPostProcessorExample.MyConfig'

12:37:06.994 [main] INFO org.springframework.context.annotation.ConfigurationClassPostProcessor - 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'.

12:37:07.067 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'

12:37:07.068 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'

12:37:07.069 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'

12:37:07.071 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'

12:37:07.079 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBeanName'

12:37:07.117 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBeanName': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'strProp' of bean class [com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample$MyNewBean]: Bean property 'strProp' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBeanName': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'strProp' of bean class [com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample$MyNewBean]: Bean property 'strProp' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1736)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1444)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)

 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)

 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)

 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)

 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)

 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)

 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)

 at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)

 at com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample.main(BeanDefinitionRegistryPostProcessorExample.java:15)

Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'strProp' of bean class [com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample$MyNewBean]: Bean property 'strProp' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

 at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)

 at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426)

 at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278)

 at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266)

 at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97)

 at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1732)

 ... 12 more

Error 2:



Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBeanName': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'strProp' of bean class [com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample$MyNewBean]: Bean property 'strProp' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1736)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1444)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)

 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)

 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)

 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)

 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)

 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)

 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)

 at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)

 at com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample.main(BeanDefinitionRegistryPostProcessorExample.java:15)

Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'strProp' of bean class [com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample$MyNewBean]: Bean property 'strProp' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

 at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)

 at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426)

 at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278)

 at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266)

 at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97)

 at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77)

 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1732)

 ... 12 more

Error 3:

Check the name of the bean that registered with BeanDefinitionRegistry..registerBeanDefinition("myNewBean"). 
You should use the same bean name when looking up in the ApplicationContext.

12:44:33.582 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myNewbean'
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myNewBean' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:808)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1279)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108)
at com.javaprogramto.springboot.SpringBootCofigurations.BeanDefinitionRegistryPostProcessorExample.main(BeanDefinitionRegistryPostProcessorExample.java:18)

4. Conclusion

In conclusion, You've learned how to register the beans with Spring at runtime using BeanDefinitionRegistryPostProcessor interface.


All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: BeanDefinitionRegistryPostProcessor - Spring Boot Bean Registration Runtime Example
BeanDefinitionRegistryPostProcessor - Spring Boot Bean Registration Runtime Example
A quick guide to how to register a bean in spring with beandefinitionregistrypostprocessor interface dynamically at runtime. Created an example to get bean at runtime and possible exceptions.
https://1.bp.blogspot.com/-sDC2SOINw-0/Xr-2e7iEN6I/AAAAAAAACuw/NTjNqrXgxLQZVOdM3BtzZyZlSMsrq1yeQCLcBGAsYHQ/s640/BeanDefinitionRegistryPostProcessor%2B-%2BSpring%2BBoot%2BBean%2BRegistration%2BRuntime%2BExample-min.png
https://1.bp.blogspot.com/-sDC2SOINw-0/Xr-2e7iEN6I/AAAAAAAACuw/NTjNqrXgxLQZVOdM3BtzZyZlSMsrq1yeQCLcBGAsYHQ/s72-c/BeanDefinitionRegistryPostProcessor%2B-%2BSpring%2BBoot%2BBean%2BRegistration%2BRuntime%2BExample-min.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/spring-beandefinitionregistrypostprocessor.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/spring-beandefinitionregistrypostprocessor.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content