Spring扩展接口-InstantiationAwareBeanPostProcessor
简介
在bean创建过程中,Spring提供了扩展接口InstantiationAwareBeanPostProcessor扩展bean创建功能。
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
throws BeansException;
}
该接口有三个方法:
- postProcessBeforeInstantiation
在目标bean开始实例化前调用该方法,实现该方法可以实现返回bean的代理而非bean本身。如果返回的Object不为空,那么则说明这个类不需要Spring来进行实例化且后序自动装配、bean初始化回调等也不会被执行,该bean直接放到Spring容器中。
- postProcessAfterInstantiation
在bean被实例化之后,在Spring属性填充(from explicit properties or autowiring)发生之前。当然返回结果为true时,说明应该为bean设置属性。如果返回结果为false,跳过bean属性赋值环节。
- postProcessPropertyValues
在工厂将给定的属性值应用于给定的bean之前,对其进行后处理。
用途示例
Spring代理AbstractAutoProxyCreator
postProcessBeforeInstantiation方法,尝试创建一个代理对象返回。
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = getCacheKey(beanClass, beanName);
if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
if (beanName != null) {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
}
return null;
}
更多信息请移步Spring专栏:www.yuque.com/mrhuang-ire…
参考: [1].blog.csdn.net/J080624/art…
本文来自博客园,作者:扎Zn了老Fe,转载请注明原文链接:https://www.cnblogs.com/itThinking/p/17771114.html