Thursday, 8 February 2018

How to use BeanPostProcessor ?


Rarely used.
Can be used to see the logs of bean loading, dependency resolution etc. or to get more control with customization.
It is generic and will be called for all the beans.

Make a generic service class by implementing BeanPostProcessor interface and override its 2 methods.

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

  @Override
  public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
        System.out.println("postProcessAfterInitialization : " + name);
        return bean;

  }

  @Override
  public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
        System.out.println("postProcessBeforeInitialization : " + name);
        return bean;
    }   
}



Going one step further, we can use another interface BeanFactoryPostProcessor to provide the Abstract factory implementation for your post processor.
Normally, very rarely used.

Implements BeanFactoryPostProcessor interface and override its 1 method.

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
        factory.addBeanPostProcessor(new MyBeanPostProcessor());
    }
}


No comments:

Post a Comment

Note: only a member of this blog may post a comment.