Spring的 AOP
<aop:aspectj-autoproxy/> 开启注解支持
/**
aop表达式的含义:
execution(* cn.itcast.service..*.*(..))
执行
* ---->任何返回值类型 (java.lang.String) (!void 返回值类型非void类型)
cn.itcast.service ---->包名
.. ----->子包 下的类也要拦截 // 一个点 . 表示只对service包下的类进行拦截
* ----->所有类
. ----->下的所有
* ----->所有方法
(..) 方法的参数,两个点表示,有参数也可以没有参数.2.(java.lang.String,..) 一个参数类型为String,第二个参宿可以有也可以没有
*/
@Aspect //该类为切面类
@Component //将切面类交给Spring容器管理
public class Demo
{
//切入点:定义要拦截的方法.
@Pointcut(" execution(*cn.itcast.service..*.*(..)) ") //(aop的表达式语言)
private void anyMethod(){} //声明一个切入点的名称
//切入点名称 args(userName)获取参数
@Before("anyMethod() && args(userName) ") //定义前置通知
public void doAccessCheck( String userName)
{
System.out.println(" 前置通知 ");
}
// retruning 拦截方法的返回数据
@AfterReturning( pointcut ="anyMethod()",retruning="result") //后置通知
public void doAfterReturning( String result )
{
System.out.println("---后置通知--"); //先打印 前置通知 拦截的方法 后置通知
}
@After(" anyMethod() ") //最终通知
public void doAfter()
{
System.out.println(" 最终通知 "); // 先打印 前置通知 拦截的方法 后置通知 最终通知
}
@AfterThrowing(" anyMethod() ") //异常通知(有了异常通知则不会执行后置通知)
public void doAfter()
{
System.out.println(" 异常通知 ");
}
@Around(" anyMethod() ") //环绕通知 类似于Struts2的烂机器 做权限判断
public Object doBasicProfiling( ProceedingJoinPoint pjp ) throws Throwable
{
System.out.println(" 进入方法 ");
Object result = pjp.proceed();//一定要执行该方法
System.out.println(" 退出方法 ");
return result;
}
//执行顺序:前置通知 --->进入方法---> 拦截的方法---> 后置通知---> 最终通知---> 退出方法
}
XML配置的方式
<bean id = "log" class ="包名.切面类"> <aop:config> <aop:aspect id = "myaop" ref ="log"> // 切面 <aop:pointcut id = "mycut" expression ="execution(* cn.itcast.service..*.*(..))" /> //切入点 <aop:before pointcut-ref = "mycut" method = "doAccessCheck"/> //前置通知 <aop:after-returning pointcut-ref="mycut" method="doReturnCheck"/> //后置通知 <aop:after-throwing pointcut-ref="mycut" method="doExceptionAction"/> // 异常通知 <aop:after pointcut-ref="mycut" method="doReleaseAction"/> //最终通知 <aop:around pointcut-ref="mycut" method="doBasicProfiling"/> //环绕通知 </aop:aspect> </aop:config>
浙公网安备 33010602011771号