Spring学习笔记
源码阅读篇Spring AOP源码分析Spring AOP核心类解析Spring AOP基础解析类AOP联盟定义的接口Spring AOP中定义的类Advisor系列(重点)Pointcut系列(重点)MethodMatcher系列(重点)Advised系列ProxyConfig系列TargetSource系列AopProxy系列(重点)AopProxyFactory系列AdvisorChainFactory系列AdvisorAdapterRegistry系列AutoProxyUtils系列Advice实现系列(重点)AbstractAspectJAdvice系列(重点)AdvisorAdapter系列(重点)AspectJAdvisorFactory系列BeanFactoryAspectJAdvisorsBuilder系列AspectInstanceFactory系列ProxyMethodInvocation系列ClassFilter系列(重点)
查找BeanDefinitionParser流程分析找入口流程图流程解析
执行BeanDefinitionParser流程分析找入口流程图流程解析
产生AOP代理流程分析AspectJAwareAdvisorAutoProxyCreator的继承体系找入口流程解析
AOP代理对象执行流程找入口流程解析
事务流程源码分析获取TransactionInterceptor的BeanDefinition找入口流程图流程解析
执行TransactionInterceptor流程分析找入口流程解析
源码阅读篇
Spring AOP源码分析
Spring AOP核心类解析
Spring AOP基础解析类
类名作用概述
AopNamespaceHandlerAOP命名空间解析类。我们在用AOP的时候,会在Spring配置文件的beans标签中引入:xmlns:aop。AspectJAutoProxyBeanDefinitionParser解析<aop:aspectj-autoproxy />标签的类。在AopNamespaceHandler中创建的类。ConfigBeanDefinitionParser解析<aop:config /> 标签的类。同样也是在AopNamespaceHandler中创建的类。AopNamespaceUtilsAOP命名空间解析工具类,在上面两个中被引用。AopConfigUtilsAOP配置工具类。主要是向Spring容器中注入可以生成Advisor和创建代理对象的bean。
AOP联盟定义的接口
接口名作用概述
AdviceAOP联盟中的一个标识接口,通知和Interceptor顶级类。我们说的各种通知类型都要实现这个接口。InterceptorAOP联盟中进行方法拦截的一个标识接口,是Advice的子类。MethodInterceptor方法拦截器,是Interceptor的一个重要子接口。主要方法:invoke;入参为:MethodInvocation。ConstructorInterceptor构造方法拦截器,是Interceptor的另一个重要的子接口。在AOP联盟中是可以对构造方法进行拦截的,这样的场景我们应该很少用到。主要方法为,construct;入参为ConstructorInvocation。JoinpointAOP联盟中的连接点接口。主要的方法是:proceed()执行下一个拦截器。getThis()获取目标对象。InvocationAOP拦截的执行接口,是Joinpoint的子接口。主要方法:getArguments()获取参数。MethodInvocationInvocation的一个重要子接口,真正执行AOP方法的拦截。主要方法:getMethod()获取目标方法。ConstructorInvocationInvocation的另一个重要子接口,执行构造方法的拦截。主要方法:getConstructor()返回构造方法。
Spring AOP中定义的类
Advisor系列(重点)
类名作用概述
AdvisorSpringAOP中的核心类,组合了Advice。PointcutAdvisorSpringAOP中Advisor的重要子接口。 组合了切点Pointcut和Advice。InstantiationModelAwarePointcutAdvisorImplPointcutAdvisor的一个重要实现子类。DefaultPointcutAdvisorPointcutAdvisor的另一个重要实现子类。 可以将Advice包装为Advisor。 在SpringAOP中是以Advisor为主线,向Advice靠拢。
Pointcut系列(重点)
类名作用概述
PointcutSpringAOP中切点的顶级抽象类。TruePointcutPointcut的一个重要实现类。在DefaultPointcutAdvisor中使用的是TruePointcut。在进行切点匹配的时候永远返回true。AspectJExpressionPointcutPointcut的一个重要实现类,AspectJ语法切点类。同时实现了MethodMatcher,AspectJ语法切点的匹配在这个类中完成。AnnotationMatchingPointcutPointcut的一个重要实现类,注解语法的切点类。JdkRegexpMethodPointcutPointcut的一个重要实现类,正则语法的切点类。
MethodMatcher系列(重点)
类名作用概述
MethodMatcher切点匹配连接点的地方:即类中的某个方法和我们定义的切点表达式是否匹配、能不能被AOP拦截。TrueMethodMatcher用于返回true。AnnotationMethodMatcher带有注解的方法的匹配器。
Advised系列
类名作用概述
AdvisedSpringAOP中的又一个核心接口。它组合了Advisor和TargetSource即目标对象AdvisedSupportAdvised的一个实现类,SpringAOP中的一个核心类。继承了ProxyConfig实现了Advised。ProxyCreatorSupportAdvisedSupport的子类。引用了AopProxyFactory用来创建代理对象。ProxyFactoryProxyCreatorSupport的子类,用来创建代理对象。在SpringAOP中用的最多。ProxyFactoryBeanProxyCreatorSupport的子类,用来创建代理对象。它实现了BeanFactoryAware、FactoryBean接口。AspectJProxyFactoryProxyCreatorSupport的子类,用来创建代理对象。使用AspectJ语法。
ProxyConfig系列
类名作用概述
ProxyConfigSpringAOP中的一个核心类。在Advised中定义了一系列的配置接口,例如:是否暴露对象、是否强制使用CGlib等。ProxyConfig是对这些接口的实现,但是ProxyConfig却不是Advised的实现类。ProxyProcessorSupportProxyConfig的子类。AbstractAutoProxyCreatorProxyProcessorSupport的重要子类,SpringAOP中的核心类。实现了SmartInstantiationAwareBeanPostProcessor、BeanFactoryAware接口。自动创建代理对象的类。我们在使用AOP的时候基本上都是用的这个类来进行Bean的拦截,创建代理对象。AbstractAdvisorAutoProxyCreatorAbstractAutoProxyCreator的子类,SpringAOP中的核心类,用来创建Advisor和代理对象。AspectJAwareAdvisorAutoProxyCreatorAbstractAdvisorAutoProxyCreator的子类,使用AspectJ语法创建Advisor和代理对象。AnnotationAwareAspectJAutoProxyCreatorAspectJAwareAdvisorAutoProxyCreator的子类。使用AspectJ语法创建Advisor和代理对象的类。<aop:aspectj-autoproxy />标签默认注入到SpringAOP中的BeanDefinition。InfrastructureAdvisorAutoProxyCreatorAbstractAdvisorAutoProxyCreator的子类,SpringAOP中的核心类,基础建设类,Spring事务默认的创建代理对象的类。
TargetSource系列
类名作用概述
TargetSource持有目标对象的接口。SingletonTargetSourceTargetSource的子类,适用于单例目标对象。HotSwappableTargetSourceTargetSource的子类,支持热交换的目标对象。AbstractRefreshableTargetSourceTargetSource的子类,支持可刷新的热部署的目标对象。AbstractBeanFactoryBasedTargetSourceTargetSource的子类,实现了BeanFactoryAware接口。SimpleBeanTargetSourceAbstractBeanFactoryBasedTargetSource的子类,从BeanFactory中获取单例Bean。LazyInitTargetSourceAbstractBeanFactoryBasedTargetSource的子类,从BeanFactory中获取单例Bean。支持延迟初始化。AbstractPrototypeBasedTargetSourceAbstractBeanFactoryBasedTargetSource的子类,对Prototype类型的Bean的支持。ThreadLocalTargetSourceAbstractPrototypeBasedTargetSource的子类,和线程上下文相结合的类。PrototypeTargetSourceAbstractPrototypeBasedTargetSource的子类,从BeanFacory中获取Prototype 类型的Bean。
AopProxy系列(重点)
类名作用概述
AopProxy定义生成AOP代理对象的类的接口规范。JdkDynamicAopProxyAopProxy的实现类,使用JDK的方式创建代理对象。它持有Advised对象,实现了AopProxy接口和InvocationHandler接口。CglibAopProxyAopProxy的实现类,使用Cglib的方法创建代理对象。它持有 Advised对象。ObjenesisCglibAopProxyCglibAopProxy的子类,使用Cglib的方式创建代理对象。它持有Advised对象。
AopProxyFactory系列
类名作用概述
AopProxyFactory创建AOP代理对象的工厂类的接口,择使用JDK还是Cglib的方式来创建代理对象。DefaultAopProxyFactoryAopProxyFactory的子类,也是SpringAOP中唯一默认的实现类。
AdvisorChainFactory系列
类名作用概述
AdvisorChainFactory获取Advisor链的接口。DefaultAdvisorChainFactoryAdvisorChainFactory的实现类。也是SpringAOP中唯一默认的 实现类。
AdvisorAdapterRegistry系列
类名作用概述
AdvisorAdapterRegistryAdvisor适配注册器类接口,用来将Advice适配为Advisor。将Advisor适配为MethodInterceptor。DefaultAdvisorAdapterRegistryAdvisorAdapterRegistry的实现类。也是SpringAOP中唯一默认的实现类。持有:MethodBeforeAdviceAdapter、AfterReturningAdviceAdapter、ThrowsAdviceAdapter实例。
AutoProxyUtils系列
类名作用概述
AutoProxyUtilsSpringAOP自动创建代理对象的工具类。
Advice实现系列(重点)
AspectJ有五种通知类型,其中三种是直接可以强转成MethodInterceptor接口。
类名作用概述
BeforeAdvice前置通知接口,直接继承了Advice接口。MethodBeforeAdviceBeforeAdvice的子接口,定义了方法before,执行前置通知。MethodBeforeAdviceInterceptorMethodBefore前置通知Interceptor,实现了MethodInterceptor接口,持有MethodBeforeAdvice对象。AfterAdvice后置通知接口,直接继承了Advice接口。ThrowsAdvice后置异常通知接口,直接继承了AfterAdvice接口。AfterReturningAdvice后置返回通知接口,直接继承了AfterAdvice接口。AfterReturningAdviceInterceptor后置返回通知Interceptor,实现了MethodInterceptor和 AfterAdvice接口,持有AfterReturningAdvice实例ThrowsAdviceInterceptor后置异常通知Interceptor,实现了MethodInterceptor和 AfterAdvice接口,要求方法名为:afterThrowing
AbstractAspectJAdvice系列(重点)
类名作用概述
AbstractAspectJAdvice使用AspectJ注解的通知类型顶级父类。AspectJMethodBeforeAdvice使用AspectJ Before注解的前置通知类型。实现了MethodBeforeAdvice,继承了AbstractAspectJAdvice。AspectJAfterAdvice使用AspectJ After注解的后置通知类型。实现了 MethodInterceptor、AfterAdvice接口,继承了 AbstractAspectJAdvice。AspectJAfterReturningAdvice使用AspectJ AfterReturning注解的后置通知类型。实现了 AfterReturningAdvice、AfterAdvice接口,继承了 AbstractAspectJAdvice。AspectJAroundAdvice使用AspectJ Around注解的后置通知类型。实现了 MethodInterceptor接口,继承了AbstractAspectJAdvice。AspectJAfterThrowingAdvice使用AspectJ Around注解的后置通知类型。实现了 MethodInterceptor、AfterAdvice接口,继承了AbstractAspectJAdvice。
AdvisorAdapter系列(重点)
类名作用概述
AdvisorAdapterAdvisor适配器,判断此接口的是不是能支持对应的Advice。五种通知类型,只有三种通知类型适配器。这里可以想一下为什么只有三种。MethodBeforeAdviceAdapter前置通知的适配器,支持前置通知类。有一个getInterceptor方法:将 Advisor适配为MethodInterceptor。Advisor持有Advice类型的实例, 获取MethodBeforeAdvice,将MethodBeforeAdvice适配为 MethodBeforeAdviceInterceptor。AOP的拦截过程通过 MethodInterceptor来完成。AfterReturningAdviceAdapter后置返回通知的适配器,支持后置返回通知类。有一个getInterceptor 方法:将Advisor适配为MethodInterceptor。Advisor持有Advice类型的实例,获取AfterReturningAdvice,将AfterReturningAdvice适配为 AfterReturningAdviceInterceptor。AOP的拦截过程通过 MethodInterceptor来完成。ThrowsAdviceAdapter后置异常通知的适配器,支持后置异常通知类。有一个getInterceptor 方法:将Advisor适配为MethodInterceptor。Advisor持有Advice类型的实例,获取ThrowsAdvice,将ThrowsAdvice适配为 ThrowsAdviceInterceptor。AOP的拦截过程通过MethodInterceptor来完成。
AspectJAdvisorFactory系列
类名作用概述
AspectJAdvisorFactory使用AspectJ注解生成Advisor工厂类AbstractAspectJAdvisorFactoryAspectJAdvisorFactory的子类,使用AspectJ注解生成Advisor的工 厂类。ReflectiveAspectJAdvisorFactoryAbstractAspectJAdvisorFactory的子类,使用AspectJ注解生成 Advisor的具体实现类。AspectMetadata使用AspectJ Aspect注解的切面元数据类。
BeanFactoryAspectJAdvisorsBuilder系列
类名作用概述
BeanFactoryAspectJAdvisorsBuilder工具类,负责构建Advisor、Advice,是SpringAOP核心类。
AspectInstanceFactory系列
类名作用概述
AspectInstanceFactoryAspect实例工厂类接口MetadataAwareAspectInstanceFactoryAspectInstanceFactory的子接口,含有Aspect注解元数据 Aspect切面实例工厂类。BeanFactoryAspectInstanceFactoryMetadataAwareAspectInstanceFactory的实现类,持有BeanFactory实例。从 BeanFactory中获取Aspect实例。PrototypeAspectInstanceFactoryBeanFactoryAspectInstanceFactory的子类,获取Prototype类型的Aspect实例。SimpleMetadataAwareAspectInstanceFactoryMetadataAwareAspectInstanceFactory的实现类,在AspectJProxyFactory中有使用。SingletonMetadataAwareAspectInstanceFactoryMetadataAwareAspectInstanceFactory的实现类,继承了 SimpleAspectInstanceFactory。单例Aspect实例类,在AspectJProxyFactory中有使 用。SimpleBeanFactoryAwareAspectInstanceFactoryAspectInstanceFactory的实现类,同时实现了BeanFactoryAware接口。和aop:config配合使用的类。
ProxyMethodInvocation系列
类名作用概述
ProxyMethodInvocation含有代理对象,MethodInvocation的子接口。ReflectiveMethodInvocationProxyMethodInvocation的实现类,AOP拦截的执行入口类。CglibMethodInvocationReflectiveMethodInvocation的子类,对Cglib反射调用目标方法进行了一点改进。
ClassFilter系列(重点)
查找BeanDefinitionParser流程分析
根据自定义标签,找到对应的BeanDefinitionParser,比如aop:config标签,就对应着ConfigBeanDefinitionParser。阅读经验分享:根据自定义标签名称冒号前面的值去直接找NamespaceHandler,然后再根据自定义标签名称冒号后面的值去找BeanDefinitionParser。
找入口
DefaultBeanDefinitionDocumentReader#parseBeanDefinitions方法的第16行或者23行:
protected void parseBeanDefinitions(Element root
, BeanDefinitionParserDelegate delegate
) {
if (delegate
.isDefaultNamespace(root
)) {
NodeList nl
= root
.getChildNodes();
for (int i
= 0; i
< nl
.getLength(); i
++) {
Node node
= nl
.item(i
);
if (node
instanceof Element) {
Element ele
= (Element
) node
;
if (delegate
.isDefaultNamespace(ele
)) {
parseDefaultElement(ele
, delegate
);
}
else {
delegate
.parseCustomElement(ele
);
}
}
}
}
else {
delegate
.parseCustomElement(root
);
}
}
流程图
流程解析
BeanDefinitionParserDelegate#parseCustomElement
@Nullable
public BeanDefinition
parseCustomElement(Element ele
, @Nullable BeanDefinition containingBd
) {
String namespaceUri
= getNamespaceURI(ele
);
if (namespaceUri
== null
) {
return null
;
}
NamespaceHandler handler
= this.readerContext
.getNamespaceHandlerResolver().resolve(namespaceUri
);
if (handler
== null
) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri
+ "]", ele
);
return null
;
}
return handler
.parse(ele
, new ParserContext(this.readerContext
, this, containingBd
));
}
DefaultNamespaceHandlerResolver#resolve
@Override
@Nullable
public NamespaceHandler
resolve(String namespaceUri
) {
Map
<String, Object> handlerMappings
= getHandlerMappings();
Object handlerOrClassName
= handlerMappings
.get(namespaceUri
);
if (handlerOrClassName
== null
) {
return null
;
}
else if (handlerOrClassName
instanceof NamespaceHandler) {
return (NamespaceHandler
) handlerOrClassName
;
}
else {
String className
= (String
) handlerOrClassName
;
try {
Class
<?> handlerClass
= ClassUtils
.forName(className
, this.classLoader
);
if (!NamespaceHandler
.class.isAssignableFrom(handlerClass
)) {
throw new FatalBeanException("Class [" + className
+ "] for namespace [" + namespaceUri
+
"] does not implement the [" + NamespaceHandler
.class.getName() + "] interface");
}
NamespaceHandler namespaceHandler
= (NamespaceHandler
) BeanUtils
.instantiateClass(handlerClass
);
namespaceHandler
.init();
handlerMappings
.put(namespaceUri
, namespaceHandler
);
return namespaceHandler
;
}
}
}
AopNamespaceHandler#init
@Override
public void init() {
registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());
registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
}
至此,找到了解析<aop:config></aop:config>对应的BeanDefinitionParser
执行BeanDefinitionParser流程分析
解析aop:config标签,最终解析10个类对应的BeanDefinition
产生代理对象的类对应的BeanDefinition(一种):
AspectJAwareAdvisorAutoProxyCreator 通知BeanDefinition(五种):
AspectJMethodBeforeAdviceAspectJAfterAdviceAspectJAfterReturningAdviceAspectJAfterThrowingAdviceAspectJAroundAdvice 通知器BeanDefinition(两种):
DefaultBeanFactoryPointcutAdvisorAspectJPointcutAdvisor 切入点BeanDefinition(一种):
AspectJExpressionPointcut 用于产生自定义增强类实例的类对应的BeanDefinition:实例工厂去产生自定义功能对应的类的实例
SimpleBeanFactoryAwareAspectInstanceFactory----增强类的实例 用于调用自定义增强类方法对应的BeanDefinition:使用一个封装增强方法的BeanDefinition去封装Method方法
MethodLocatingFactoryBean—Method对象
找入口
NamespaceHandlerSupport类的parse方法的第6行代码:
@Override
@Nullable
public BeanDefinition
parse(Element element
, ParserContext parserContext
) {
BeanDefinitionParser parser
= findParserForElement(element
, parserContext
);
return (parser
!= null
? parser
.parse(element
, parserContext
) : null
);
}
流程图
流程解析
ConfigBeanDefinitionParser#parse
@Override
@Nullable
public BeanDefinition
parse(Element element
, ParserContext parserContext
) {
CompositeComponentDefinition compositeDef
=
new CompositeComponentDefinition(element
.getTagName(), parserContext
.extractSource(element
));
parserContext
.pushContainingComponent(compositeDef
);
configureAutoProxyCreator(parserContext
, element
);
List
<Element> childElts
= DomUtils
.getChildElements(element
);
for (Element elt
: childElts
) {
String localName
= parserContext
.getDelegate().getLocalName(elt
);
if (POINTCUT
.equals(localName
)) {
parsePointcut(elt
, parserContext
);
}
else if (ADVISOR
.equals(localName
)) {
parseAdvisor(elt
, parserContext
);
}
else if (ASPECT
.equals(localName
)) {
parseAspect(elt
, parserContext
);
}
}
parserContext
.popAndRegisterContainingComponent();
return null
;
}
ConfigBeanDefinitionParser#parsePointcut
private AbstractBeanDefinition
parsePointcut(Element pointcutElement
, ParserContext parserContext
) {
String id
= pointcutElement
.getAttribute(ID
);
String expression
= pointcutElement
.getAttribute(EXPRESSION
);
AbstractBeanDefinition pointcutDefinition
= null
;
try {
this.parseState
.push(new PointcutEntry(id
));
pointcutDefinition
= createPointcutDefinition(expression
);
}
finally {
this.parseState
.pop();
}
return pointcutDefinition
;
}
↓↓↓↓↓
protected AbstractBeanDefinition
createPointcutDefinition(String expression
) {
RootBeanDefinition beanDefinition
= new RootBeanDefinition(AspectJExpressionPointcut
.class);
beanDefinition
.setScope(BeanDefinition
.SCOPE_PROTOTYPE
);
beanDefinition
.setSynthetic(true);
beanDefinition
.getPropertyValues().add(EXPRESSION
, expression
);
return beanDefinition
;
}
spring-aop.xml配置文件:
<aop:config>
<aop:aspect ref="myAdvice">
<aop:after method="after" pointcut="execution(* *..*.*ServiceImpl.*(..))" />
<aop:before method="before" pointcut="execution(* *..*.*ServiceImpl.*(..))" />
</aop:aspect>
</aop:config>
ConfigBeanDefinitionParser#parseAspect:
private void parseAspect(Element aspectElement
, ParserContext parserContext
) {
String aspectId
= aspectElement
.getAttribute(ID
);
String aspectName
= aspectElement
.getAttribute(REF
);
try {
NodeList nodeList
= aspectElement
.getChildNodes();
boolean adviceFoundAlready
= false;
for (int i
= 0; i
< nodeList
.getLength(); i
++) {
Node node
= nodeList
.item(i
);
if (isAdviceNode(node
, parserContext
)) {
AbstractBeanDefinition advisorDefinition
= parseAdvice(
aspectName
, i
, aspectElement
, (Element
) node
, parserContext
, beanDefinitions
, beanReferences
);
beanDefinitions
.add(advisorDefinition
);
}
}
AspectComponentDefinition aspectComponentDefinition
= createAspectComponentDefinition(
aspectElement
, aspectId
, beanDefinitions
, beanReferences
, parserContext
);
parserContext
.pushContainingComponent(aspectComponentDefinition
);
List
<Element> pointcuts
= DomUtils
.getChildElementsByTagName(aspectElement
, POINTCUT
);
for (Element pointcutElement
: pointcuts
) {
parsePointcut(pointcutElement
, parserContext
);
}
parserContext
.popAndRegisterContainingComponent();
}
finally {
this.parseState
.pop();
}
}
ConfigBeanDefinitionParser#parseAdvice:产生了8个BeanDefinition
private AbstractBeanDefinition
parseAdvice(String aspectName
, int order
, Element aspectElement
, Element adviceElement
, ParserContext parserContext
, List
<BeanDefinition> beanDefinitions
, List
<BeanReference> beanReferences
) {
try {
this.parseState
.push(new AdviceEntry(parserContext
.getDelegate().getLocalName(adviceElement
)));
RootBeanDefinition methodDefinition
= new RootBeanDefinition(MethodLocatingFactoryBean
.class);
methodDefinition
.getPropertyValues().add("targetBeanName", aspectName
);
methodDefinition
.getPropertyValues().add("methodName", adviceElement
.getAttribute("method"));
methodDefinition
.setSynthetic(true);
RootBeanDefinition aspectFactoryDef
=
new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory
.class);
aspectFactoryDef
.getPropertyValues().add("aspectBeanName", aspectName
);
aspectFactoryDef
.setSynthetic(true);
AbstractBeanDefinition adviceDef
= createAdviceDefinition(
adviceElement
, parserContext
, aspectName
, order
, methodDefinition
, aspectFactoryDef
,
beanDefinitions
, beanReferences
);
RootBeanDefinition advisorDefinition
= new RootBeanDefinition(AspectJPointcutAdvisor
.class);
advisorDefinition
.setSource(parserContext
.extractSource(adviceElement
));
advisorDefinition
.getConstructorArgumentValues().addGenericArgumentValue(adviceDef
);
if (aspectElement
.hasAttribute(ORDER_PROPERTY
)) {
advisorDefinition
.getPropertyValues().add(
ORDER_PROPERTY
, aspectElement
.getAttribute(ORDER_PROPERTY
));
}
parserContext
.getReaderContext().registerWithGeneratedName(advisorDefinition
);
return advisorDefinition
;
}
finally {
this.parseState
.pop();
}
}
↓↓↓↓↓
private AbstractBeanDefinition
createAdviceDefinition(Element adviceElement
, ParserContext parserContext
, String aspectName
, int order
, RootBeanDefinition methodDef
, RootBeanDefinition aspectFactoryDef
, List
<BeanDefinition> beanDefinitions
, List
<BeanReference> beanReferences
) {
RootBeanDefinition adviceDefinition
= new RootBeanDefinition(getAdviceClass(adviceElement
, parserContext
));
adviceDefinition
.setSource(parserContext
.extractSource(adviceElement
));
adviceDefinition
.getPropertyValues().add(ASPECT_NAME_PROPERTY
, aspectName
);
adviceDefinition
.getPropertyValues().add(DECLARATION_ORDER_PROPERTY
, order
);
if (adviceElement
.hasAttribute(RETURNING
)) {
adviceDefinition
.getPropertyValues().add(
RETURNING_PROPERTY
, adviceElement
.getAttribute(RETURNING
));
}
if (adviceElement
.hasAttribute(THROWING
)) {
adviceDefinition
.getPropertyValues().add(
THROWING_PROPERTY
, adviceElement
.getAttribute(THROWING
));
}
if (adviceElement
.hasAttribute(ARG_NAMES
)) {
adviceDefinition
.getPropertyValues().add(
ARG_NAMES_PROPERTY
, adviceElement
.getAttribute(ARG_NAMES
));
}
ConstructorArgumentValues cav
= adviceDefinition
.getConstructorArgumentValues();
cav
.addIndexedArgumentValue(METHOD_INDEX
, methodDef
);
Object pointcut
= parsePointcutProperty(adviceElement
, parserContext
);
if (pointcut
instanceof BeanDefinition) {
cav
.addIndexedArgumentValue(POINTCUT_INDEX
, pointcut
);
beanDefinitions
.add((BeanDefinition
) pointcut
);
}
else if (pointcut
instanceof String) {
RuntimeBeanReference pointcutRef
= new RuntimeBeanReference((String
) pointcut
);
cav
.addIndexedArgumentValue(POINTCUT_INDEX
, pointcutRef
);
beanReferences
.add(pointcutRef
);
}
cav
.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX
, aspectFactoryDef
);
return adviceDefinition
;
}
↓↓↓↓↓
private Class
<?> getAdviceClass(Element adviceElement
, ParserContext parserContext
) {
String elementName
= parserContext
.getDelegate().getLocalName(adviceElement
);
if (BEFORE
.equals(elementName
)) {
return AspectJMethodBeforeAdvice
.class;
}
else if (AFTER
.equals(elementName
)) {
return AspectJAfterAdvice
.class;
}
else if (AFTER_RETURNING_ELEMENT
.equals(elementName
)) {
return AspectJAfterReturningAdvice
.class;
}
else if (AFTER_THROWING_ELEMENT
.equals(elementName
)) {
return AspectJAfterThrowingAdvice
.class;
}
else if (AROUND
.equals(elementName
)) {
return AspectJAroundAdvice
.class;
}
else {
throw new IllegalArgumentException("Unknown advice kind [" + elementName
+ "].");
}
}
产生AOP代理流程分析
AspectJAwareAdvisorAutoProxyCreator的继承体系
|--BeanPostProcessor
postProcessBeforeInitialization--初始化之前调用
postProcessAfterInitialization--初始化之后调用
|--InstantiationAwareBeanPostProcessor
postProcessBeforeInstantiation--实例化之前调用
postProcessAfterInstantiation--实例化之后调用
InstantiationPropertyValues--后置处理属性值
|--SmartInstantiationAwareBeanPostProcessor
predictBeanType
determineCandidateConstructors
getEarlyBeanReference
|--AbstractAutoProxyCreator
postProcessBeforeInitialization
postProcessAfterInitialization--AOP功能入口
postProcessBeforeInitialization
postProcessAfterInitialization
postProcessPropertyValues
...
|--AbstractAdvisorAutoProxyCreator
getAdvicesAndAdvisorsForBean
findEligibleAdvisors
findCandidateAdvisors
findAdvisorsThatCanApply
|--AspectJAwareAdvidorAutoProxyCreator
extendAdvisors
sortAdvisors
找入口
AbstractAutoProxyCreator类的postProcessAfterInitialization方法第6行代码
public Object
postProcessAfterInitialization(@Nullable Object bean
, String beanName
) throws BeansException
{
if (bean
!= null
) {
Object cacheKey
= getCacheKey(bean
.getClass(), beanName
);
if (this.earlyProxyReferences
.remove(cacheKey
) != bean
) {
return wrapIfNecessary(bean
, beanName
, cacheKey
);
}
}
return bean
;
}
流程解析
AbstractAutoProxyCreator#wrapIfNecessary:
protected Object
wrapIfNecessary(Object bean
, String beanName
, Object cacheKey
) {
if (StringUtils
.hasLength(beanName
) && this.targetSourcedBeans
.contains(beanName
)) {
return bean
;
}
if (Boolean
.FALSE
.equals(this.advisedBeans
.get(cacheKey
))) {
return bean
;
}
if (isInfrastructureClass(bean
.getClass()) || shouldSkip(bean
.getClass(), beanName
)) {
this.advisedBeans
.put(cacheKey
, Boolean
.FALSE
);
return bean
;
}
Object
[] specificInterceptors
= getAdvicesAndAdvisorsForBean(bean
.getClass(), beanName
, null
);
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
;
}
↓↓↓↓↓
protected Object
createProxy(Class
<?> beanClass
, @Nullable String beanName
,
@Nullable Object
[] specificInterceptors
, TargetSource targetSource
) {
if (this.beanFactory
instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils
.exposeTargetClass((ConfigurableListableBeanFactory
) this.beanFactory
, beanName
, beanClass
);
}
ProxyFactory proxyFactory
= new ProxyFactory();
proxyFactory
.copyFrom(this);
if (!proxyFactory
.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass
, beanName
)) {
proxyFactory
.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass
, proxyFactory
);
}
}
Advisor
[] advisors
= buildAdvisors(beanName
, specificInterceptors
);
proxyFactory
.addAdvisors(advisors
);
proxyFactory
.setTargetSource(targetSource
);
customizeProxyFactory(proxyFactory
);
proxyFactory
.setFrozen(this.freezeProxy
);
if (advisorsPreFiltered()) {
proxyFactory
.setPreFiltered(true);
}
return proxyFactory
.getProxy(getProxyClassLoader());
}
ProxyFactory#getProxy:
public Object
getProxy(@Nullable ClassLoader classLoader
) {
return createAopProxy().getProxy(classLoader
);
}
ProxyCreatorSupport#createAopProxy:
protected final synchronized AopProxy
createAopProxy() {
if (!this.active
) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
小结:
1、产生代理对象流程:先要获取AopProxyFactory(DefaultAopProxyFactory),接下来去产生AopProxy(JDKDynamicAopProxy、CglibDynamicAopProxy)2、AopProxy,本身即是产生代理对象(Proxy)直接工厂,又是代理对象调用时需要的InvocationHandler实现类。 DefaultAopProxyFactory#createAopProxy:
public AopProxy
createAopProxy(AdvisedSupport config
) throws AopConfigException
{
if (config
.isOptimize() || config
.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config
)) {
Class
<?> targetClass
= config
.getTargetClass();
if (targetClass
.isInterface() || Proxy
.isProxyClass(targetClass
)) {
return new JdkDynamicAopProxy(config
);
}
return new ObjenesisCglibAopProxy(config
);
}
else {
return new JdkDynamicAopProxy(config
);
}
}
JdkDynamicAopProxy#getProxy:
@Override
public Object
getProxy(@Nullable ClassLoader classLoader
) {
Class
<?>[] proxiedInterfaces
= AopProxyUtils
.completeProxiedInterfaces(this.advised
, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces
);
return Proxy
.newProxyInstance(classLoader
, proxiedInterfaces
, this);
}
AOP代理对象执行流程
找入口
主要去针对Jdk产生的动态代理对象进行分析,其实就是去分析InvocationHandler的invoke方法。入口:JdkDynamicAopProxy#invoke方法:
public Object
invoke(Object proxy
, Method method
, Object
[] args
) throws Throwable
{
try {
List
<Object> chain
= this.advised
.getInterceptorsAndDynamicInterceptionAdvice(method
, targetClass
);
else {
invocation
= new ReflectiveMethodInvocation(proxy
, target
, method
, args
, targetClass
, chain
);
retVal
= invocation
.proceed();
}
return retVal
;
}
}
流程解析
一个目标对象,如果被多个增强功能给增强的话,那么增强功能的执行顺序是有两个保证:如果通知类型相同的增强功能的执行顺序,由XML中配置的顺序所影响;如果是不同通知类型相同的增强功能的执行顺序,由对应的MethodInterceptor的实现来保证顺序,比如MethodBeforeAdviceInterceptor,就是先不管其他的通知功能,先执行自己的通知功能。DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice
public List
<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config
, Method method
, @Nullable Class
<?> targetClass
) {
List
<Object> interceptorList
= new ArrayList<Object>(config
.getAdvisors().length
);
Class
<?> actualClass
= (targetClass
!= null
? targetClass
: method
.getDeclaringClass());
boolean hasIntroductions
= hasMatchingIntroductions(config
, actualClass
);
AdvisorAdapterRegistry registry
= GlobalAdvisorAdapterRegistry
.getInstance();
for (Advisor advisor
: config
.getAdvisors()) {
if (advisor
instanceof PointcutAdvisor) {
PointcutAdvisor pointcutAdvisor
= (PointcutAdvisor
) advisor
;
if (config
.isPreFiltered() || pointcutAdvisor
.getPointcut().getClassFilter().matches(actualClass
)) {
MethodMatcher mm
= pointcutAdvisor
.getPointcut().getMethodMatcher();
if (MethodMatchers
.matches(mm
, method
, actualClass
, hasIntroductions
)) {
MethodInterceptor
[] interceptors
= registry
.getInterceptors(advisor
);
if (mm
.isRuntime()) {
for (MethodInterceptor interceptor
: interceptors
) {
interceptorList
.add(new InterceptorAndDynamicMethodMatcher(interceptor
, mm
));
}
}
else {
interceptorList
.addAll(Arrays
.asList(interceptors
));
}
}
}
}
else if (advisor
instanceof IntroductionAdvisor) {
IntroductionAdvisor ia
= (IntroductionAdvisor
) advisor
;
if (config
.isPreFiltered() || ia
.getClassFilter().matches(actualClass
)) {
Interceptor
[] interceptors
= registry
.getInterceptors(advisor
);
interceptorList
.addAll(Arrays
.asList(interceptors
));
}
}
else {
Interceptor
[] interceptors
= registry
.getInterceptors(advisor
);
interceptorList
.addAll(Arrays
.asList(interceptors
));
}
}
return interceptorList
;
}
DefaultAdvisorAdapterRegistry#getInterceptors:
public MethodInterceptor
[] getInterceptors(Advisor advisor
) throws UnknownAdviceTypeException
{
List
<MethodInterceptor> interceptors
= new ArrayList<>(3);
Advice advice
= advisor
.getAdvice();
if (advice
instanceof MethodInterceptor) {
interceptors
.add((MethodInterceptor
) advice
);
}
for (AdvisorAdapter adapter
: this.adapters
) {
if (adapter
.supportsAdvice(advice
)) {
interceptors
.add(adapter
.getInterceptor(advisor
));
}
}
if (interceptors
.isEmpty()) {
throw new UnknownAdviceTypeException(advisor
.getAdvice());
}
return interceptors
.toArray(new MethodInterceptor[0]);
}
ReflectiveMethodInvocation#proceed
public Object
proceed() throws Throwable
{
if (this.currentInterceptorIndex
== this.interceptorsAndDynamicMethodMatchers
.size() - 1) {
return invokeJoinpoint();
}
Object interceptorOrInterceptionAdvice
=
this.interceptorsAndDynamicMethodMatchers
.get(++this.currentInterceptorIndex
);
if (interceptorOrInterceptionAdvice
instanceof InterceptorAndDynamicMethodMatcher) {
InterceptorAndDynamicMethodMatcher dm
=
(InterceptorAndDynamicMethodMatcher
) interceptorOrInterceptionAdvice
;
if (dm
.methodMatcher
.matches(this.method
, this.targetClass
, this.arguments
)) {
return dm
.interceptor
.invoke(this);
}
else {
return proceed();
}
}
else {
return ((MethodInterceptor
) interceptorOrInterceptionAdvice
).invoke(this);
}
}
AopUtils#invokeJoinpointUsingReflection
public static Object
invokeJoinpointUsingReflection(@Nullable Object target
, Method method
, Object
[] args
)
throws Throwable
{
try {
ReflectionUtils
.makeAccessible(method
);
return method
.invoke(target
, args
);
}
}
事务流程源码分析
获取TransactionInterceptor的BeanDefinition
找入口
AbstractBeanDefinitionParser#parse方法
@Override
@Nullable
public final BeanDefinition
parse(Element element
, ParserContext parserContext
) {
AbstractBeanDefinition definition
= parseInternal(element
, parserContext
);
if (definition
!= null
&& !parserContext
.isNested()) {
try {
String id
= resolveId(element
, definition
, parserContext
);
if (!StringUtils
.hasText(id
)) {
parserContext
.getReaderContext().error(
"Id is required for element '" + parserContext
.getDelegate().getLocalName(element
)
+ "' when used as a top-level tag", element
);
}
String
[] aliases
= null
;
if (shouldParseNameAsAliases()) {
String name
= element
.getAttribute(NAME_ATTRIBUTE
);
if (StringUtils
.hasLength(name
)) {
aliases
= StringUtils
.trimArrayElements(StringUtils
.commaDelimitedListToStringArray(name
));
}
}
BeanDefinitionHolder holder
= new BeanDefinitionHolder(definition
, id
, aliases
);
registerBeanDefinition(holder
, parserContext
.getRegistry());
if (shouldFireEvents()) {
BeanComponentDefinition componentDefinition
= new BeanComponentDefinition(holder
);
postProcessComponentDefinition(componentDefinition
);
parserContext
.registerComponent(componentDefinition
);
}
}
catch (BeanDefinitionStoreException ex
) {
String msg
= ex
.getMessage();
parserContext
.getReaderContext().error((msg
!= null
? msg
: ex
.toString()), element
);
return null
;
}
}
return definition
;
}
流程图
流程解析
执行TransactionInterceptor流程分析
找入口
TransactionInterceptor类实现了MethodInterceptor接口,所以入口方法是invoke方法:
@Override
@Nullable
public Object
invoke(final MethodInvocation invocation
) throws Throwable
{
Class
<?> targetClass
= (invocation
.getThis() != null
? AopUtils
.getTargetClass(invocation
.getThis()) : null
);
return invokeWithinTransaction(invocation
.getMethod(), targetClass
, invocation
::proceed
);
}
流程解析