How to Use Ordered Interface to Arrange Order Sequence of BeanPostProcessor Java Spring Bean in Java Spring Application

Posted on

Introduction

This article will show how to use a Java Bean implementing BeanPostProcessor interface in a Java Spring Application. As in the previous article, a Java Bean implementing BeanPostProcessor. It exist in the article with the title of ‘How to Use BeanPostProcessor in Java Spring Bean Application’ in this link. Using the base application exist in the article with the title of ‘How to Create a Simple Java Spring Application using NetBeans IDE’ in this link. What is actually the differentiation of the BeanPostProcessor usage from the previous one. Well, in this article, not only using one Java Spring Bean implementing the BeanPostProcessor, but also another one which makes the two of them. Furthermore, not only use the two of them, but use it in a sequence order with the help of Ordered interface.

 

Using Ordered Interface with BeanPostProcessor Interface in Java Spring Bean

The following are the steps for demonstrating the usage of two Java Spring Beans in an order. Implementing the Java Spring Beans will force or will require to implement the usage of the postProcessBeforeInitialization and postProcessAfterInitialization method. Both of the method’s execution has each own sequence. The postProcessBeforeInitialization’s execution is right before the init method of the Java Spring Bean instantiation or generation. On the other hand, the postProcessAfterInitialization’s execution is right after the init method of the Java Spring Bean. But what if there are more than one Java Spring Beans implementing the BeanPostProcessor which is going to be executed in a certain order ?. The answer is very simple which is by implementing an additional interface with the name of ‘Ordered’.

Steps for implementing Ordered Interface and BeanPostProcessor Interface in Java Spring Bean

  1. First of all, register the two Java Spring Beans implementing Ordered and BeanPostProcessor interface. For an example, the first one in sequence execution is the Java Spring Bean with the name of ‘EmployeeRegisterBeanPostProcessor’. The next sequence’s execution is the other bean with the name of ‘EmployeeTestBeanPostProcessor’. Register it in the Spring Configuration file with the name of ‘spring-config.xml’ in the ‘src/main/resources’ as an example. Just do it like in the following content :

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="employeeBean" class="com.test.spring.Employee" init-method="init" destroy-method="destroy">
    </bean>
          <bean class="com.test.spring.EmployeeTestBeanPostProcessor" />
          <bean class="com.test.spring.EmployeeRegisterBeanPostProcessor" />
    </beans>
  2. After defining the it, just create the Java Spring Bean as in the Spring Configuration file definition. The first one is ‘EmployeeTestBeanPostProcessor as in the following content :

    package com.test.spring;
    
    import org.springframework.beans.factory.config.BeanPostProcessor;
    import org.springframework.core.Ordered;
    
    public class EmployeeTestBeanPostProcessor implements BeanPostProcessor, Ordered {
         @Override
         public Object postProcessBeforeInitialization(Object args, String status){
                System.out.println("Before executing the init method of the "+args+" object. EmployeeTestBeanPostProcessor[postProcessBeforeInitialization]: Applicants enroll the test as part of the selection process");
                return args;
         }
    
         @Override
         public Object postProcessAfterInitialization(Object args, String status){
                System.out.println("After executing the init method of the "+args+" object. EmployeeTestBeanPostProcessor[postProcessAfterInitialization]: Applicants receive the test result of the selection process");
                return args;
         }
    
         @Override
         public int getOrder() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                System.out.println("EmployeeTestBeanPostProcessor : Applicants enroll the test in the selection process to join the company... ");
                return 1;
         }
    }

    The most important thing to decide the sequence of the order’s execution of the Java Spring Bean is in the value returned by the getOrder() method. In the above Java Spring Bean, it has the value of 1. The lower the value, the higher the priority to be executed as soon as possible in the first place.

  3. The next one is the EmployeeRegisterBeanPostProcessor. Just create and implement the BeanPostProcessor and the Ordered interface. It is exactly the same with the previous Java Spring Bean with the name of ‘EmployeeTestBeanPostProcessor’ but with a different name. Another part which are totally different is the content or the statement inside each methods. The following is the actual content of that Java Spring Bean :

  4. package com.test.spring;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    import org.springframework.core.Ordered;
    
    public class EmployeeRegisterBeanPostProcessor implements BeanPostProcessor, Ordered {
    
           @Override
           public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                  //return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName); //To change body of generated methods, choose Tools | Templates.
                  System.out.println("Before executing the init method of the "+bean+" object. EmployeeRegisterBeanPostProcessor[postProcessBeforeInitialization]: Applicants register to the human resource department for selection process to join the company");
                  return bean;
           }
    
           @Override
           public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                  //return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName); //To change body of generated methods, choose Tools | Templates.
                  System.out.println("After executing the init method of the "+bean+" object. EmployeeRegisterBeanPostProcessor[postProcessAfterInitialization]: Applicants contact the human resource department asking for the result of the selection process");
                  return bean;
           }
    
           @Override
           public int getOrder() {
                  //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                  System.out.println("EmployeeRegisterBeanPostProcessor : Applicants register in the selection process to join the company... ");
                  return 0;
           }
    }

    As in the first Java Spring Bean, it is also very important thing to decide the sequence of the order’s execution of the Java Spring Bean is in the value returned by the getOrder() method. In the second Java Spring Bean above, it has the value of 0. It will have the higher priority to be executed in the first place compared with ‘EmployeeTestBeanPostProcessor which has the value of 1.

Steps for executing Ordered Interface and BeanPostProcessor Interface in Java Spring Bean

  1. First of all, it is important to describe the Java Spring Bean which is running with the init method. In this example, it is a Java file with the name of ‘Employee.java’. The following is the content of the file :

    package com.test.spring;
    
    import java.util.List;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    
    public class Employee {
           private String id;
    
           public void setId(String id) {
                  this.id = id;
           }
    
           public void init(){
                  System.out.println("Employee is going through the init method by passing the test to join the Company... ");
           }
    
           public void destroy(){
                  System.out.println("Employee is going through the destroy method by resigning from the Company... ");
           }
    
           public void identifyID(){
                  System.out.println("I am an "+this.id+" !");
           }
    }

    Don’t forget to define the Java Spring Bean also in the ‘spring-config.xml’ located in ‘src/main/resources’ as an example. The full complete content of it exist above. But as an information, below is a line which is define only the ‘Employee’ bean with the init and destroy method definition. Just in case to highlight it :

    <bean id="employeeBean" class="com.test.spring.Employee" init-method="init" destroy-method="destroy">
  2. Another important thing is to have a main Java file which acts as the running program for demonstration. The following is the actual content of it :

    package com.test.spring;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.AbstractApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringMain {
           public static void main(String[] args){
                  ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    
                  ((AbstractApplicationContext) context).registerShutdownHook();
    
                  Employee employee = (Employee) context.getBean("employeeBean");
                  employee.setId("Employee of the Company");
                  employee.identifyID();
           }
    }
  3. Last but not least, just execute the program to prove that the sequence of the execution for both of the Java Spring Bean. It will execute the ‘EmployeeRegisterBeanPostProcessor’ and then the ‘EmployeeTestBeanPostProcessor’ according tothe value of the getOrder() method. The first execution’s order is the one with the lower value. It is obvious that the first execution will be the ‘EmployeeRegisterBeanPostProcessor’ since it has the returning value of 0 from the getOrder() method. On the other hand, the next execution will be the ‘EmployeeTestBeanPostProcessor’  since it has the returning value of 1 from the getOrder() method.

    The execution have the following output :

     

    Scanning for projects...
    --------------------------< com.test:spring >---------------------------
    Building spring 1.0-SNAPSHOT
    --------------------------------[ jar ]---------------------------------
    
    --- exec-maven-plugin:1.2.1:exec (default-cli) @ spring ---
    EmployeeRegisterBeanPostProcessor : Applicants register in the selection process to join the company...
    EmployeeTestBeanPostProcessor : Applicants enroll the test in the selection process to join the company...
    Before executing the init method of the com.test.spring.Employee@51565ec2 object. EmployeeRegisterBeanPostProcessor[postProcessBeforeInitialization]: Applicants register to the human resource department for selection process to join the company
    Before executing the init method of the com.test.spring.Employee@51565ec2 object. EmployeeTestBeanPostProcessor[postProcessBeforeInitialization]: Applicants enroll the test as part of the selection process
    Employee is going through the init method by passing the test to join the Company...
    After executing the init method of the com.test.spring.Employee@51565ec2 object. EmployeeRegisterBeanPostProcessor[postProcessAfterInitialization]: Applicants contact the human resource department asking for the result of the selection process
    After executing the init method of the com.test.spring.Employee@51565ec2 object. EmployeeTestBeanPostProcessor[postProcessAfterInitialization]: Applicants receive the test result of the selection process
    I am an Employee of the Company !
    Employee is going through the destroy method by resigning from the Company...
    ------------------------------------------------------------------------
    BUILD SUCCESS
    ------------------------------------------------------------------------
    Total time: 1.094 s
    Finished at: 2021-09-14T19:01:14+07:00
    ------------------------------------------------------------------------
    

Leave a Reply