先看下接口定义:
/**
* Factory hook that allows for custom modification of an application context's
* bean definitions, adapting the bean property values of the context's underlying
* bean factory.
* ......
* @author Juergen Hoeller
* @author Sam Brannen
* @since 06.07.2003
* @see BeanPostProcessor
* @see PropertyResourceConfigurer
*/
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory 办法上的形容:(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
对于 BeanFactoryPostProcessor 这个接口,正文是这样说的:这是一个扩大点,它提供了使用者批改利用上下文里的 bean definitions, 改写 bean factory 上下文里的 bean 属性值。这里额定贴一下 BeanDefinition 这个类上的正文:
/**
* A BeanDefinition describes a bean instance, which has property values,
* constructor argument values, and further information supplied by
* concrete implementations.
* .....
**/
而后咱们再来看一下 BeanFactoryPostProcessor 的 postProcessBeanFactory 办法上的形容:在 bean definition 已被加载(如将从 xml 文件解析进去的 bean 入到了 beanDefinitionMap 里)但还没被实例化的时候,能够批改这些 bean definition 的属性。
接着再看下 BeanFactoryPostProcessor 的子类:
咱们来写个示例来批改下 bean definition,这里有个 Person 类,它有一个 name 属性,看配置文件:<id="person" "name"="Zhao"/>
当初咱们想给这个 Person 对象动静增加一个属性:
class CustomBeanDefinitionRegistryPostProcessor implements BeanFactoryPostProcessor {
/**
* @param configurableListableBeanFactory
* @throws BeansException
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition("person");
PropertyValue propertyValue = new PropertyValue("interest","writing");
beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
}
}
class Person{
private String name;
//get(),set()
}
下面这个是对已有的 bean definition 进行属性批改,那是否动静新增一个 bean 到 spring 上下文里呢?应用 BeanFactoryPostProcessor 的子类 BeanDefinitionRegistryPostProcessor 是能够的:
class CustomBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
/**
* @param beanDefinitionRegistry
* @throws BeansException
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {RootBeanDefinition beanDefinition = new RootBeanDefinition(Person.class);
beanDefinitionRegistry.registerBeanDefinition("person",beanDefinition);
}
}
class Person{
private String name;
//get(),set()
}
对于一个一般的 Person 对象,咱们通过重写 postProcessBeanDefinitionRegistry 办法将其退出到了 spring IOC 容器里了。