1.AOP关键术语
1.target:目标类,需要被代理的类。例如:UserService
2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法
3.PointCut 切入点:已经被增强的连接点。例如:addUser()
4.advice 通知/增强,增强代码。例如:after、before
5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
6.proxy 代理类:通知+切入点
7. Aspect(切面): 是切入点pointcut和通知advice的结合
AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想,是个比较经典的例子。
2.AOP 的通知类型
(1) Spring按照通知Advice在目标类方法的连接点位置,可以分为5类
-
前置通知org.springframework.aop.MethodBeforeAdvice
在目标方法执行前实施增强,比如上面例子的 before()方法 -
后置通知 org.springframework.aop.AfterReturningAdvice
在目标方法执行后实施增强,比如上面例子的 after()方法 -
环绕通知 org.aopalliance.intercept.MethodInterceptor
在目标方法执行前后实施增强 -
异常抛出通知 org.springframework.aop.ThrowsAdvice
在方法抛出异常后实施增强 -
引介通知 org.springframework.aop.IntroductionInterceptor
在目标类中添加一些新的方法和属性
3.使用 Spring AOP 解决上面的需求
<!--创建目标类-->
<bean id="eatImpl1" class="com.zhiyou100.dao.impl.EatImpl1"></bean>
<!--创建切面类-->
<bean id="myTransaction" class="com.zhiyou100.MyTransaction"></bean>
<aop:config>
<!--切入点表达式-->
<!--任意公共方法的执行-->
<!--execution(public * *(..))-->
<!--任何一个以set开头的方法-->
<!--execution(* set*(..))-->
<!--定义EatImpl1的所有方法-->
<!--execution(* com.zhiyou100.dao.impl.EatImpl.*(..))-->
<aop:pointcut id="pointcut" expression="execution(* com.zhiyou100.dao.impl.*.*(..))"></aop:pointcut>
<aop:aspect ref="myTransaction">
<!--前置通知-->
<aop:before method="prepare" pointcut-ref="pointcut"></aop:before>
<!--后置通知-->
<aop:after-returning method="beforeOver" pointcut-ref="pointcut" returning="o"></aop:after-returning>
<!--抛出异常通知-->
<aop:after-throwing method="throwBeforeOver" pointcut-ref="pointcut" throwing="throwable"></aop:after-throwing>
<!--最终通知-->
<aop:after method="after" pointcut-ref="pointcut"></aop:after>
<!--环绕通知-->
<aop:around method="myAround" pointcut-ref="pointcut"></aop:around>
</aop:aspect>
</aop:config>