关于Spring的BeanPostProcessor
BeanPostProcessor接口作用是:如果我们需要在Spring容器完成Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现,然后注册到容器中。、
比如如果我们使用spring整合hibernate,我们可以在容器实例化前先加载hibernate的配置文件:
public class MappingFactoryBean implements FactoryBean {
private static Logger log = LoggerFactory
.getLogger(MappingFactoryBean.class);
public Object getObject() throws Exception {
List<String> configs = ApplicationContext.getContext().getApplication()
.getMappingConfigs();
log.debug("************* hibernate configs: " + configs);
return configs.toArray(new String[configs.size()]);
}
public Class<?> getObjectType() {
return String[].class;
}
public boolean isSingleton() {
return true;
}
}
public class MappingAutowiring implements BeanPostProcessor {
private static Logger log = LoggerFactory
.getLogger(MappingAutowiring.class);
private String[] mappingResources;
public String[] getMappingResources() {
return mappingResources;
}
public void setMappingResources(String[] mappingResources) {
this.mappingResources = mappingResources;
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof LocalSessionFactoryBean) {
log.debug("============ MappingAutowiring: " + mappingResources);
((LocalSessionFactoryBean) bean)
.setMappingResources(mappingResources);
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
}
beans.xml 配置如下:
<bean id="mappingAutowiring"
class="xx.MappingAutowiring">
<property name="mappingResources" ref="mappingResources" />
</bean>
<bean id="mappingResources"
class="xx.MappingFactoryBean" />