Spring的AOP是Spring的两大特性之一,在分析源码之前,先介绍AOP之中的几个术语。
Advice通知:
Advice定义在连接点做什么,为切面挣钱提供织入接口,在Spring AOP中,它主要描述Spring AOP围绕方法调用而注入的切面行为。(do what?)
Pointcut切点:
Pointcut决定Advice通知应该作用于哪个两节点,也就是说通过Pointcut来定义需要增强的方法的集合,这些集合的选取可以按照一定的规则来完成。这种情况下,Pointcut通常意味着标识方法,例如,这些需要增强的地方可以由某个正则表达式进行标识,或根据某个方法名进行匹配等。(do where?)
Advisor通知器:
完成对目标方法的切面增强设计(Advice)和关注点设计(Pointcut)以后,需要一个对象把它们结合起来,完成这个作用的就是Adivsor。(do where and what?)
Spring中实现Aop的方式有多种,我们分析以xml配置aop的方式进行源码分析。
测试代码如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="targetClass" class="TargetClass" lazy-init="true"></bean>
<bean id="testAdvice" class="TestAdvice"></bean>
<aop:config proxy-target-class="true">
<aop:aspect id="test" ref="testAdvice">
<aop:pointcut id="allMethod" expression="execution(* TargetI.*(..))"></aop:pointcut>
<aop:before method="before" pointcut-ref="allMethod"></aop:before>
<aop:after method="after" pointcut-ref="allMethod"></aop:after>
</aop:aspect>
</aop:config>
</beans>
public class TargetClass implements TargetI{
@Override
public void test() {
System.out.println("test run....");
}
}
public interface TargetI {
public void test();
}
public class TestAdvice {
public void before(){
System.out.println("run before...");
}
public void after(){
System.out.println("run after...");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass
{
public static void main(String [] args)
{
ApplicationContext ap