zyllt / project

随便写写
1 stars 0 forks source link

Spring源码之AOP的实现方式 #10

Open zyllt opened 6 years ago

zyllt commented 6 years ago

1、启用AOP的配置方式

<aop:aspectj-autoproxy proxy-target-class="false"/>

这个AOP标签在解析的时候做了什么呢?

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
    extendBeanDefinition(element, parserContext);
    return null;
}
zyllt commented 6 years ago

1、基于注解的,需要配置aspectj-autoproxy;

2、还有一种是基于XML文件的,需要配置config,advisor等

zyllt commented 6 years ago

第一种是在解析的时候会注册一个AspectJAwareAdvisorAutoProxyCreator,这个类继承自InstantiationAwareBeanPostProcessor的,具体对被注入了AOP的bean在实例化之前会调用AbstractAutoProxyCreator#postProcessBeforeInstantiation,在此中会生成代理对象。 如果配置了proxy-target-class=true或者该类没有接口,使用cglib来生成一个子类。如果为false并且有接口则使用jdk的proxy

        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;
            }
        }