Case 5: Using BeanPostProcessor

We will use the same Ch02_Bean_Life_Cycle project that we developed in Case1.

Follow these steps:

  1. Add Demo_BeanPostProcessorDemo_ class in the com.ch02.processor package, which implements BeanPostProcessor.
  2. Override the postProcessBeforeInitialization() method.
  3. Override the postProcessAfterInitialization() method.
  4. The complete class definition is shown in the following piece of code:
public class Demo_BeanPostProcessor implements BeanPostProcessor { 
  @Override 
  public Object postProcessBeforeInitialization(Object bean, 
  String beanName) throws BeansException { 
    // TODO Auto-generated method stub 
  System.out.println("initializing bean before init:-  
    "+beanName); 
  return bean; 
} 
 
@Override 
public Object postProcessAfterInitialization(Object bean,String
beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("initializing bean after init:- "+beanName); return bean; } }
  1. Add one more bean to the beans_life cycle.xml file as follows:
<bean id="beanPostProcessor" 
class="com.ch02.processor.Demo_BeanPostProcessor"/> 
  1. Create a Test_BeanPostProcessor class with the main method. We don't have to ask the bean for beanPostProcessor, as its methods are called before and after the init method for each bean in the container.
  2. Write the test code to find the order of methods called in the initialization process, as shown in the following code snippet:
public class Test_BeanPostProcessor { 
   public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    ApplicationContext context=new 
       ClassPathXmlApplicationContext("beans_life cycle.xml"); 
     Demo_BeanPostProcessor obj=  
(Demo_BeanPostProcessor)context.getBean("beanPostProcessor"); System.out.println(obj); } }
  1. The output is as follows:

The underlined statements are for the bean that we asked from the container. However, find the order that is followed as a constructor-the postProcessBeforeInitialization method, the custom-init method, and postProcessAfterInitialization.

In an application, more than one BeanPostProcessors can be configured. The order of their execution can be managed by setting the order property if the bean implements an Ordered interface. The scope of each PostBeanProcessor is per container.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.127.197