鍍金池/ 問答/Java/ 關(guān)于Spring的InstantiationAwareBeanPostProce

關(guān)于Spring的InstantiationAwareBeanPostProcessor接口的一個疑問?

關(guān)于Spring的InstantiationAwareBeanPostProcessor,其會在bean對象實例化之前調(diào)用其相關(guān)的接口,例如接口:

postProcessBeforeInstantiation

關(guān)于該接口,文檔中有解釋:

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也可能會返回代理對象是為什么呢?什么場景下會有這種需求呢?

回答
編輯回答
蔚藍(lán)色

同樣在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;
}
2018年1月5日 07:08