Searching...
Sunday, 16 June 2013

Spring Bean Post Processor example

12:13

The   BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations.  

Example

1. XML Configuration

<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-2.5.xsd">

    <bean id="studentBean" class="com.vinod.test.Student" scope="singleton">
    </bean>
         <bean class="com.vinod.test.MyBeanPostProcessor" />
</beans>
 

2. Create a class which Bean post processor interface

package com.vinod.test;

import org.springframework.beans.BeansException;

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

public class MyBeanPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before Initialization : " + beanName);
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After Initialization : " + beanName);
        return bean;
    }
}

3. Student.java
 
package com.vinod.test;

public class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3. Test class

package com.vinod.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringCoreScopeTest {

    public static void main(String arg[]) {
        // Getting beans from XML based bean configuration
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml");
        // Student bean
        Student obj = (Student) context.getBean("studentBean");
        obj.setName("vinod");
        System.out.println(obj.getName());
       

    }
}
  

4. Output
 
 

Before Initialization : studentBean

After Initialization : studentBean

vinod

0 comments: