关于Spring的InstantiationAwareBeanPostProcessor接口的一个疑问?

siege
  • 29

关于Spring的InstantiationAwareBeanPostProcessor,其会在bean对象实例化之前调用其相关的接口,例如接口:

postProcessBeforeInstantiation

关于该接口,文档中有解释:

Apply this BeanPostProcessor before the target bean gets instantiated.The returned bean object may be a proxy to use instead of the target bean,effectively suppressing default instantiation of the target bean.

意思是说该接口也可以返回代理对象,那么问题来了:

一般我们的Aop代理对象的生成都是在BeanPostProcessor 的postProcessAfterInitialization方法中

    /**
     * Create a proxy with the configured interceptors if the bean is
     * identified as one to proxy by the subclass.
     * @see #getAdvicesAndAdvisorsForBean
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean != null) {
            Object cacheKey = getCacheKey(bean.getClass(), beanName);
            if (!this.earlyProxyReferences.contains(cacheKey)) {
                return wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
    }

其中wrapIfNecessary就是生成代理对象的方法

请教大家,那么InstantiationAwareBeanPostProcessor中的postProcessBeforeInstantiation也可能会返回代理对象是为什么呢?什么场景下会有这种需求呢?

回复
阅读 1.4k
1 个回答

同样在Spring AOP中,也有生成代理的。

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws {

..................
    // 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.
    TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            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;
}
你知道吗?

宣传栏