In XML file
<bean id="triangle" class="com.company.aop.model.Triangle">
<property name="name" value="myTriangle"></property>
</bean>
<bean class="com.company.aop.DisplayNameBeanPostProcessor"></bean>
In DisplayNameBeanPostProcessor.java class
public class DisplayNameBeanPostProcessor implements BeanPostProcessor{
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
// TODO Auto-generated method stub
if(bean instanceof Triangle) {
// System.out.println("Tr "+(((Triangle) bean).getName().toString()));
System.out.println("I am after intialisation");
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
// TODO Auto-generated method stub
if(bean instanceof Triangle) {
System.out.println("Tr "+(((Triangle) bean).getName().toString()));
}
return bean;
}
}
Now when i run this code, it goes to postProcessBeforeInitialization() method with argument bean and beanName and prints the message "myTriangle". This bean has information like its name field with value "myTriangle" in my case. But the method signature says that it is before initialisation then what is this bean that has been passed into it if it has not been initialised yet ? And what is the difference between
public Object postProcessAfterInitialization(Object bean, String beanName)
and
public Object postProcessBeforeInitialization(Object bean, String beanName)
Why this line
System.out.println("Tr "+(((Triangle) bean).getName().toString()));
prints the name in method postProcessBeforeInitialization if the method has been called before initialisation ?
You can refer to the section 5.8.1 of the Spring docs here. The key point here is that the "postProcessBeforeInitialization" should be read as "postProcessBeforeInitializationCallback" and "postProcessAfterInitialization" should be read as "postProcessAfterInitializationCallback". So these are pre and post processeors after the before/after initialization callback are run by the Spring container on the bean. This is what is conveyed in the docs of these methods here too.
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
Apply this BeanPostProcessor to the given new bean instance before any bean initialization callbacks (like InitializingBean's afterPropertiesSet or a custom init-method). The bean will already be populated with property values.
Note it says that "The bean will already be populated with property values". Similarly
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
Apply this BeanPostProcessor to the given new bean instance after any bean initialization callbacks (like InitializingBean's afterPropertiesSet or a custom init-method). The bean will already be populated with property values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With