Spring

Spicy Spring : Dynamically create your own BeanDefinition

Posted on by  
Willem Cheizoo

When we a have Spring managed application, we want to let Spring manage all of our beans. Beside the regular way of creating beans with known solutions like Annotated beans, Java Configuration and XML Configuration, there is also a way in which we can create our own BeanDefinition. With a BeanDefinitionRegistryPostProcessor it is possible to create a specific post processor which can add BeanDefinitions to the BeanDefinitionRegistry. It differs from the BeanPostProcessor, which only has hooks for Bean Initialization (construction of your POJO), where the BeanDefinitionRegistryPostProcessor has a hook on the BeanDefinitionRegistry. This gives us the ability to define our own BeanDefinition. First we create a BeanDefinitionRegistryPostProcessor implementation as listed in the example. We implement the required method, and will be able to add our own bean definition to the registry. The defined BeanDefinition will be picked up by the ApplicationContext and the POJO will be constructed. Our result is A Spring managed bean

package com.jdriven;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;

@Component
public class LogicServiceRegistryPostProcessor
        implements BeanDefinitionRegistryPostProcessor {

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

        RootBeanDefinition beanDefinition =
                new RootBeanDefinition(MyServiceImpl.class); //The service implementation
        serviceDefinition.setTargetType(MyService.class); //The service interface
        serviceDefinition.setRole(BeanDefinition.ROLE_APPLICATION);
        registry.registerBeanDefinition("myBeanName", beanDefinition );
    }
}

Continue reading →

shadow-left