AOP
面向切面编程,在Spring中的作用有:一,允许用户实现自定义切面,用AOP完善OOP的使用;二,提供声明式企业服务,特别是声明式事务管理。
切面:Aspect,一个横切关注点的模块化,可能会横切多个对象。
连接点:Joinpoint,在程序执行过程中某个特定的点。
切入点:Pointcut,匹配连接点的断言,通常是一个表达式,有专门的语法,用于致命在那里嵌入横切逻辑。
通知:Active,在切面的某个特定的连接点上执行的动作。
通知类型:前置,后置,异常,最终,环绕,在连接点之前、之后、抛出异常、退出、包围连接点的通知。
目标对象:Target Object,被一个或多个切面所通知的对象。
代理对象:Proxy Object,AOP框架创建的对象,目标对象的增强版。
从Spring容器中获取对象时,容器探测该对象上的方法是否成为了连接点(被切入点表达式匹配)。如果是,Spring容器将根据连接点通知一个代理对象。客户端得到的是一个代理对象的引用,调用其方法实际上是调用代理对象上的方法,前置,环绕通知执行后,调用将抵达目标对象,目标对象的方法被调用之后后置通知将会被执行。
实践
准备工作,jar包、配置文件不说,具体代码:
业务类:
public class ServiceA{
public void addAccount(String account){
System.out.println("add account in ServiceA");
}
}
public class ServiceB{
public void deposit(){
System.out.println("deposit in ServiceB");
}
}
public class ServiceC{
public void withdraw(){
System.out.println("withdraw in ServiceC");
}
}
通知类及通知代码:
public class AopInterceptor{
//前置通知
public void somethingBefore(){
System.out.println("前置通知");
}
//后置通知
public void somethingAfter(){
System.out.println("后置通知");
}
//环绕通知
public Object somethingAround(ProceedingJoinPoint point)throws Throwable{
System.out.println("环绕通知开始");
long time = System.currentTimeMillis();
//执行连接点
Object obj = point.proceed();
System.out.println("环绕通知结束");
return obj;
}
}
AOP配置
新建配置文件,主要配置如下:
<aop:config>
<!--切入点声明-->
<aop:pointcut expression="excution(*org.bd.spring.ch02.Service*.*(..))" id="allMethodInService" />
<!--切面声明-->
<aop:aspect ref="AopInterceptor">
<!--前置-->
<aop:before method="somethingBefore" pointcut-ref="allMethodInService">
<!--后置-->
<aop:after-returning method="somethingAfter" pointcut-ref="allMethodInService">
<!--环绕-->
<aop:around method="somethingAround" pointcut-ref="allMethodInService">
</aop:aspect>
</aop:config>
切入表达式即:excution(*org.bd.spring.ch02.Service*.*(..))