前面我们讲过了经典的基于代理的AOP和基于自动代理的AOP是如何实现的,有了前面的基础,学习基于AOP标签的AOP的实现原理,就很简单了。
经典的基于代理的AOP:
https://blog.csdn.net/u011983531/article/details/80359304
基于自动代理的AOP:
https://blog.csdn.net/u011983531/article/details/80377764
我们先来看看基于aop标签的一个例子:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">
<bean id="sleepHelper" class="com.ghs.aop.SleepHelper2"/>
<aop:config>
<aop:aspect id="simpleAspect" ref="sleepHelper">
<aop:pointcut expression="execution(* *.sleep(..))" id="sleepPointcut"/>
<aop:before method="beforeSleep" pointcut-ref="sleepPointcut"/>
<aop:after method="afterSleep" pointcut-ref="sleepPointcut"/>
</aop:aspect>
</aop:config>
<bean id="human" class="com.ghs.aop.Human"/>
</beans>
基于自动代理的AOP往Spring容器中注入的DefaultAdvisorAutoProxyCreator,而基于AOP标签的AOP往Spring容器中注入的是AspectJAwareAdvisorAutoProxyCreator。
下面是解析AOP命名空间的核心代码。
public BeanDefinition parse(Element element, ParserContext parserContext) {
CompositeComponentDefinition compositeDef =
new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
parserContext.pushContainingComponent(compositeDef);
//配置AspectJAwareAdvisorAutoProxyCreator
configureAutoProxyCreator(parserContext, element);
List<Element> childElts = DomUtils.getChildElements(element);
for (Element elt: childElts) {
String localName = parserContext.getDelegate().getLocalName(elt);
//解析<aop:pointcut>,配置AspectJExpressionPointcut
if (POINTCUT.equals(localName)) {
parsePointcut(elt, parserContext);
}
//解析<aop:advisor>,配置DefaultBeanFactoryPointcutAdvisor
else if (ADVISOR.equals(localName)) {
parseAdvisor(elt, parserContext);
}
//解析<aop:aspect>
else if (ASPECT.equals(localName)) {
parseAspect(elt, parserContext);
}
}
parserContext.popAndRegisterContainingComponent();
return null;
}