Wednesday, January 19, 2022

Controlling Spring Behaviour

While developing Spring based application there are instances where we would like to get a control of the spring beans. It comes very handy when we can get a control of the Spring Factory and can customise as per the needs

1. BeanPostProcessor:

2. BeanFactoryPostProcessor: 

3. PropertyPlaceholderConfigurer : Property file location

-We can plugin some additional behaviour on top of existing definition.

- This will get called when all bean definitions will have been loaded, but no beans will have been instantiated yet.

-This allows for overriding or adding properties even to eager-initializing beans. 

- This will let you have access to all the beans that you have defined in XML or that are annotated (scanned via component-scan).

public class CustomBeanFactory implements BeanFactoryPostProcessor {

    @Override

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        for (String beanName : beanFactory.getBeanDefinitionNames()) {

            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

            // Manipulate the beanDefiniton or whatever you need to do

        }

    }

//Registering a new Bean

  GenericBeanDefinition myBeanDefinition = new GenericBeanDefinition(); 

            ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition("beanName", myBeanDefinition););


}

No comments:

Post a Comment