美文网首页spring 相关
Spring注解--AOP原理(四):业务bean与代理bean

Spring注解--AOP原理(四):业务bean与代理bean

作者: aix91 | 来源:发表于2019-01-08 17:43 被阅读0次

1. 调用finishBeanFactoryInitialization方法

在初始化容器的最后,会创建业务bean。创建bean的流程与BeanPostProcessor的创建流程一样(Spring注解--AOP原理(三):BeanPostProcessor创建与注册)。只是由于在此之前BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)已经注入到容器中,于是在创建业务bean的时候,就可以利用该后置处理器的postProcessAfterInitialization方法中的wrapIfNecessary方法来创建代理对象,进而可以对业务对象进行拦截。请参考Spring注解--AOP原理(二):AnnotationAwareAspectJAutoProxyCreator

2. wrapIfNecessary()方法,创建目标bean的代理对象

如果业务bean有代理对象,则返回代理对象;否则返回业务bean本身。

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
//获取注入到业务bean中的Advisor,也就是把切面类里面的通知方法包装成Advisor类
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
...
//创建业务bean的代理对象,该代理对象中封装了切面类里的通知方法
if (specificInterceptors != DO_NOT_PROXY) {
    this.advisedBeans.put(cacheKey, Boolean.TRUE);
    Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
    this.proxyTypes.put(cacheKey, proxy.getClass());
    return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}

最后进入DefaultAopProxyFactory类,创建代理对象

@Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
            if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                return new JdkDynamicAopProxy(config);
            }
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }

最后将代理bean注入到容器中。

相关文章

网友评论

    本文标题:Spring注解--AOP原理(四):业务bean与代理bean

    本文链接:https://www.haomeiwen.com/subject/wkzvrqtx.html