要理解AOP整体的逻辑需要理解一下Advice,Pointcut,Advisor的概念以及他们的关系。 
Advice是为Spring Bean提供增强逻辑的接口,提供了多种方法增强的方式,比如前置,后置,包裹等增强方式。看下Advice的类体系结构图:

Spring AOP体系学习总结-LMLPHP

图中定义了主要有3中类型的Advice,分别是BeforeAdvice,AfterAdvice 和 Interceptor,BeforeAdvice就是定义的就是方法的前置织入逻辑,AfterAdvice就是方法的后置织入逻辑。MethodInteceptor定义的是方法的包裹逻辑。想要分析其原理,先要看看怎么用,看一个应用的DEMO:

AfterAdvice.class:
public class AfterAdvice implements AfterReturningAdvice { @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("这个是 AfterReturning 方法!");
}
} BeforeAdvice.class:
public class BeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("这是BeforeAdvice的before方法!");
}
} CompareInterceptor.classpublic class CompareInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = null;
String stu_name = invocation.getArguments()[0].toString();
if ( stu_name.equals("dragon")){
//如果学生是dragon时,执行目标方法, result= invocation.proceed();
} else{
System.out.println("此学生是"+stu_name+"而不是dragon,不批准其加入.");
}
return result;
}
}

以上定义的分别是目标方法的前置逻辑,后置逻辑,及包裹逻辑。

目标类接口:
public interface IStudent { public void addStudent(String name);
} 目标实现类:
public class StudentImpl implements IStudent { @Override public void addStudent(String name) {
System.out.println(name);
}
}

Bean定义的配置文件:

<beans>
<bean id="beforeAdvice" class="aop.demo.demo1.BeforeAdvice"></bean>
<bean id="afterAdvice" class="aop.demo.demo1.AfterAdvice"></bean>
<bean id="compareInterceptor" class="aop.demo.demo1.CompareInterceptor">
</bean><bean id="studenttarget" class="aop.demo.demo1.StudentImpl"></bean> <bean id="student" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces">
<value>aop.demo.demo1.IStudent</value>
</property>
<property name="interceptorNames">
<list>
<value>beforeAdvice</value>
<value>afterAdvice</value>
<value>compareInterceptor</value>
</list>
</property>
<property name="target">
<ref bean="studenttarget"/>
</property> </bean>
</beans> 测试驱动类:<br>
public class DriverTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new FileSystemXmlApplicationContext("/src/main/java/aop/demo/applicationContext.xml");
IStudent person = (IStudent)ctx.getBean("student");
//person.addStudent("dragon");
person.addStudent("javadragon");
}
}

//执行结果:<br>
这是BeforeAdvice的before方法!
此学生是javadragon而不是dragon,不批准其加入.
这个是 AfterReturning 方法!
05-11 09:01