Sunday, March 20, 2011

BeanFactoryPostProcessor interface

The semantics of this interface is similar to BeanPostProcessor but with one major difference : BeanFactoryPostProcessor operate on bean configuration metadata; So spring IoC container allow BeanFactoryPostProcessor to read the configuration metadata and potentially change it before the container instantiates any bean other than BeanFactoryPostProcessor .

But if you want to change the actual bean instances( the objects that are created from the configuration metadata), then use BeanPostProcessor.

Example …

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class BeanFactoryPostProcessorImpl implements BeanFactoryPostProcessor {

public BeanFactoryPostProcessorImpl() {
System.out.println("BeanFactoryPostProcessorImpl class instantiated..");
}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
throws BeansException {
System.out.println("postProcessBeanFactory method of our BeanFactoryPostProcessorImpl class called..");

//dynamically registering a new bean in the context. you can try this later on.
//similar to @Configuration and @Bean we saw in previous section.
//factory.registerSingleton("myBean", new SampleBean());
}
}



Again one of the commonly used BeanFactoryPostProcessor is PropertyPlaceHolderConfigurer class. We already have seen the usage of this class before. This replaces the config of any bean containing ${}  with the actual property value so by the time the bean is instantiated, the correct values are already in the container.

No comments:

Post a Comment

Chitika