Sunday, March 20, 2011

Spring : BeanPostProcessor interface

The interface BeanPostProcessor allows custom modification of all new bean instance like for example making for marker interfaces or wrapping them with all proxies. The advance of interface BeanPostProcessor is that it auto-detect BeanPostProcessor beans in their bean definations and apply all beans before any others get created.

So it provides callback methods thaty you can implement to provide your own instantiation logic, dependency resolution logic and so forth. In a way you override default container's logic.

You can control the order in which these BeanPostProcessor interfaces execute by setting the order property only if the BeanPostProcessor implements the Ordered Interface.

Classes which implement BeanPostProcessor are special and treaded differently by container. All BeanPostProcessor and their directly referenced beans are instantiated on startup, as a part of the special startup phase of the ApplicationContext.

Example:

 

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

class StudentBean implements BeanPostProcessor {

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {

System.out.println("Before initialization : " + beanName);


return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {

System.out.println("After initialization : " + beanName);
return bean;
}
}



So BeanPostProcessor implementation gives us chance to perform custom processing before and after any bean is initialized.


In config.xml


<bean id="studentBean" class="com.roseindia.common.StudentBean" />

No comments:

Post a Comment

Chitika