Hi All,
I am trying to understand the application of BeanPostProcessor. I understood that postProcessBeforeInitialization() and postProcessAfterInitialization() methods are used to plugg in my code after Spring container does its.
What I don't understand is if I have multiple beans can I have customized process for each bean?
I have following codes;
This gives me following output:Code:public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } public void init(){ System.out.println("Bean is going through init."); } public void destroy(){ System.out.println("Bean will destroy now."); } } public class HelloWorld1 { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message1 : " + message); } public void init1(){ System.out.println("Bean1 is going through init."); } public void destroy1(){ System.out.println("Bean1 will destroy now."); } } public class InitHelloWorld implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("BeforeInitialization : " + beanName); return bean; // you can return any other object as well } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("AfterInitialization : " + beanName); return bean; // you can return any other object as well } } <bean id="helloWorld" class="com.anjib.beans.HelloWorld" init-method="init" destroy-method="destroy"> <property name="message" value="Hello World!"/> </bean> <bean id="helloWorld1" class="com.anjib.beans.HelloWorld1" init-method="init1" destroy-method="destroy1"> <property name="message" value="Hello World1!"/> </bean> <bean class="com.anjib.beans.InitHelloWorld" /> public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); HelloWorld1 obj1 = (HelloWorld1) context.getBean("helloWorld1"); obj1.getMessage(); context.registerShutdownHook(); } }
What I want is use InitHelloWorld for HelloWorld bean and some new InitHelloWorld1 for HelloWorld1 bean. Is that possible for I am missing fundamental concept here.Code:BeforeInitialization : helloWorld Bean is going through init. AfterInitialization : helloWorld BeforeInitialization : helloWorld1 Bean1 is going through init. AfterInitialization : helloWorld1 Your Message : Hello World! Your Message1 : Hello World1! Bean1 will destroy now. Bean will destroy now.
Any help is appreciated.
Thanks


Reply With Quote