Nearby lessons

8 of 35

Spring - BeanPostProcessor

📌 What You Will Learn
  • Understand Spring - BeanPostProcessor
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - BeanPostProcessor step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

BeanPostProcessor

In SPring Framework, when we activate ApplicationContext container then

ApplicationContext container will perform the following actions automatically with out

having developers interaction.

  • ApplicatinContext will read beans definitions from beans configuration file.
  • ApplicationContext will recognize beans classes and creates objecs for bean classes
  • ApplicationContext will perform initialization by executing initialization methods.
  • When IOCContainer is shutdown then bean objects are destroyed.

IN the above Bean lifecycle, if we want to provide customizations over beans

initializations then we have to use a predefined interface provided by Spring framework

like "org.springframework.beans.factory.config.BeanPostProcessor".

BeanPostProcessor contains the following two methods .

1.public void postProcessBeforeInitialization(Object bean, String name) throws

BeansException

--> This method will be executed just before performing bean initialization and

immediatly after bean instantiation, that is, before executing init() method if we provide

custom initialization method init().

BeanPostProcessor

BeansException

--> This method will be executed immediatly after performing beans initialization, that is,

after executing init() method if we provide custom initialization method init().

To use BeanPostPrcessor in Spring applications we have to declare an user defined class

as an implementation class to BeanPostProcessor interface , we must implement the

above specified methods and we must configure implementation class in bean

configuration file. If we provide like this then container will detect BeanPostProcessor

implementation automatically and IOCContainer will execute the BeanPostProcessor

methods in the respective locations of the beans lifecycle.

EX:

BeanPostProcessorImpl.java

package com.durgasoft.processor;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.config.BeanPostProcessor;

import com.durgasoft.beans.Customer;

public class BeanPostProcessorImpl implements BeanPostProcessor {

@Override

public Object postProcessAfterInitialization(Object bean, String name) throws

BeansException {

System.out.println("postProcessAfterInitialization()");

Customer cust=(Customer)bean;

cust.setCmobile("91-9988776655");

return cust;

}

@Override

public Object postProcessBeforeInitialization(Object bean, String name) throws

BeansException {

System.out.println("postProcessBeforeInitialization()");

Customer cust=(Customer)bean;

cust.setCemail("durga@durgasoft.com");

return cust;

}

}

Customer.java

package com.durgasoft.beans;

public class Customer {

private String cid;

private String cname;

private String caddr;

private String cemail;

private String cmobile;

public Customer(){

System.out.println("Customer Bean Object Creating");

}

public void init(){

System.out.println("Customer Bean Object Initialization through init()

method");

}

public void destroy(){

System.out.println("Customer Object Destroying through destroy()

method");

}

setXXX()

getXXX()

public void getCustomerDetails(){

System.out.println("Customer Details");

System.out.println("---------------------");

System.out.println("Customer Id :"+cid);

System.out.println("Customer Name :"+cname);

System.out.println("Customer Address:"+caddr);

System.out.println("Customer Email :"+cemail);

System.out.println("Customer Mobile :"+cmobile);

}

}

applicationContext.xml

<beans>

<bean id="cust" class="com.durgasoft.beans.Customer" init-method="init" destroy-

method="destroy">

<property name="cid" value="C-111"/>

<property name="cname" value="Durga"/>

<property name="caddr" value="Hyd"/>

</bean>

<bean class="com.durgasoft.processor.BeanPostProcessorImpl"/>

</beans>

Test.java

package com.durgasoft.test;

import org.springframework.context.support.AbstractApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.durgasoft.beans.Customer;

public class Test {

public static void main(String[] args)throws Exception {

AbstractApplicationContext context=new

ClassPathXmlApplicationContext("applicationContext.xml");

Customer cust=(Customer)context.getBean("cust");

cust.getCustomerDetails();

context.registerShutdownHook();

}

}

Inversion Of Control[IOC]

In general, in enterprise application if we need any service in our application then we have

to put request to the service provider, where service provider has to create the required

service then service provider has to send that service to the respective application.

In enterprise applications, Inversion Of Control is a design pattern or a design principle, it

will make service provider to identify the required services of the enterprise applications

and it will make the service provider to create and inject the required services to the

application with out expecting any request from the application.

IOC is available in the following two forms.

1.Dependency Lookup

2.Dependency Injection

  • Dependency Lookup

In Dependency Lookup, Service Provider will create the services and mainatined that

services either in the regisry Softwares or in the containers , where we have to perform

lookup operations inorder to get the required services.

There are two ways to get achieve Dependency lookup.

1.Dependency Pull

2.Contextualized Dependency Lookup

  • Dependecy Pull:

In Dependency Pull, Service Provider will create services and it will keep that services in any

registry softwares, where we have to perform lookup operation inorde to get the required

services, that is, pull the required services from registry softwares.

EX1: When we start application Servers like Weblogic, JBOSS , Websphere and Glassfish ,

automatically, Application Servers will create Datasource object and Application Servers

will keep that Datasource object in JNDI Server as per the server settings which we made in

application Server. In this context, we have to perform lookup(--) operation over JNDI

server on the basis of the logical name inorder to get the required Datasource object.

EX2:IN RMI Applications, User defined Registry Application will create Remote object and it

will keep that Remote object in RMIRegistry with a particular logical name , here to get the

required Remote object in Client Application we have to perform lookup operation over

RMIRegistry on the basis of the logical name.

  • Contextualized Dependency Lookup

IN this mechanism, Service Provider will create the services and manage services , in this

context, we have to perform lookup operation inorder to get the required services from

Service Provider.

EX: In general, in web applications, when we start application Server then container will

recognize all the web applications and container will deploy all the web applications into

the server, when web applications are deployed in server , container will create

ServletContext object automatically and Container will manage ServletContext object , in

this context , to get ServletContext object we have to use getServletContext() method from

GenericServlet directly with out using any reference variable, from ServletConfig object

reference and from ServletRequest object reference, that is, performing lookup operation

in Container to get ServletContext object.

  • Dependency Injection

IN this mechanism, Service Provider will create the services and inject the required services

to the application directly with out performing lookup operations and with out getting

request from client.

EX:In web applications, when we submit request to a particular Servlet , Container will

execute the requested Servlet by performing the Servlet life cycle actions like Servlet

Loading, Servlet Instantiation, Servlet Initialization , Request Processing and Servlet

Deinstantiation. In Servlet initialization phase, container will create ServletConfig object

and Container will inject ServletConfig object to the Servlet program through init(--)

method, in Request Processing phase, Container has to create request and response

objects and Container has to inject request and response objects to the Servlet program

through service() method.

public class MyServlet extends HttpServlet{

ServletConfig config;

public void init(ServletConfig config)throws ServletException{

this.config=config;

}

public void service(ServletRequest request, ServletResponse response) throws

ServletException, IOException{

----

}

}

There are two ways to achieve dependency injection.

1.Constructor Dependency Injection

2.Setter Method Dependency Injection

  • Constructor Dependency Injection

If we inject dependent values to the Bean object through Constructor then this type of

Dependency Injection is called as "Constructor Dependency Injection".

If we want to use constructor dependency injection in SPring applications , first we have to

declare the respective parameterized constructor in the corresponmding bean class then

we have to declare that constructor arguments in spring configuration file by using the

following tags.

<beans>

<bean ..... >

<constructor-arg value="--"/>

<constructor-arg> value </constructor-arg>

</bean>

----

</beans>

EX:

Course.java

------------

package com.durgasoft.beans;

public class Course {

private String cid;

private String cname;

private int ccost;

public Course(String cid, String cname, int ccost){

this.cid=cid;

this.cname=cname;

this.ccost=ccost;

}

public void getCourseDetails(){

System.out.println("Course Details");

System.out.println("-------------------");

System.out.println("Course Id :"+cid);

System.out.println("Course Name :"+cname);

System.out.println("Course Cost :"+ccost);

}

}

applicationContext.xml

<beans>

<bean id="crs" class="com.durgasoft.beans.Course">

<constructor-arg value="C-111"/>

<constructor-arg value="JAVA"/>

<constructor-arg value="5000"/>

</bean>

</beans>

Test.java

package com.durgasoft.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.durgasoft.beans.Course;

public class Test {

public static void main(String[] args)throws Exception {

ApplicationContext context=new

ClassPathXmlApplicationContext("applicationContext.xml");

Course course=(Course)context.getBean("crs");

course.getCourseDetails();

}

}

  • Setter Method Dependency Injection

If we inject dependent values to the Bean through setXXX() methods then it is called as

"Setter Method Dependency Injection".

To inject primive values and String value to the bean object then we have to use "value"

attributes in <property> or <constructor-arg> tags in beans configuration file, but, If we

want to inject User defined data types , that is, Object reference values then we have to

use "ref" attribute in <property> tag or in <constructor-arg> tag.

EX:

Account.java

package com.durgasoft.beans;

public class Account {

private String accNo;

private String accName;

private String accType;

private long balance;

setXXX()

getXXX()

}

Employee.java

package com.durgasoft.beans;

public class Employee {

private String eid;

private String ename;

private float esal;

private String eaddr;

private Account acc;

setXXX()

getXXX()

public void getEmployeeDetails(){

System.out.println("Employee Details");

System.out.println("-------------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name :"+ename);

System.out.println("Employee Salary :"+esal);

System.out.println("Employee Address:"+eaddr);

System.out.println("Account Details");

System.out.println("-------------------");

System.out.println("Account Number :"+acc.getAccNo());

System.out.println("Account Name :"+acc.getAccName());

System.out.println("Account Type :"+acc.getAccType());

System.out.println("Account Balance:"+acc.getBalance());

}

}

applicationContext.xml

<beans>

<bean id="acc" class="com.durgasoft.beans.Account">

<property name="accNo" value="abc123"/>

<property name="accName" value="Durga"/>

<property name="accType" value="Savings"/>

<property name="balance" value="25000"/>

</bean>

<bean id="emp" class="com.durgasoft.beans.Employee">

<property name="eid" value="E-111" />

<property name="ename" value="Durga"/>

<property name="esal" value="50000"/>

<property name="eaddr" value="Hyd"/>

<property name="acc" ref="acc"/>

</bean>

</beans>

Test.java

package com.durgasoft.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.durgasoft.beans.Employee;

public class Test {

public static void main(String[] args)throws Exception {

ApplicationContext context=new

ClassPathXmlApplicationContext("applicationContext.xml");

Employee emp=(Employee)context.getBean("emp");

emp.getEmployeeDetails();

}

}

Example02
JCode Cell
1 
2public void postProcessAfterInitialization(Object bean, String name) throws
3
📝 Key Takeaways
  • Key ideas of Spring - BeanPostProcessor explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end