Spring AOP 编程


package com.xcl.common;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect //用来指明这个类是切面
public class MyInterceptor {

//切入点:拦截com.impl.PersonServiceBean类下面的所有方法
//@Pointcut("execution(* com.xcl.web.action..*.*(..))")//匹配任意类型 com.xcl.web.action包以及子包下面的所有类的所有任意参数的方法
@Pointcut("execution(* com.xcl.service.impl.PersonServiceBean.*(..))")
private void anyMethod() {}//声明一个切入点

//前置通知:拦截到某个类后,先执行前置通知
//如果加args(userName),测只能拦截方法的参数为string类型的,且只有一个参数的方法
@Before("anyMethod() && args(userName)")
public void doBeforeAdvice(String userName) {
System.out.println("我是前置通知" + userName);
}
//@AfterReturning("anyMethod()")//如果不需要返回值,可以这个设置
@AfterReturning(pointcut="anyMethod()", returning="result")
public void doAfterAdvice(String result) {
System.out.println("我是后置通知" + result);
}

@After("anyMethod()")
public void doFinallyAdvice() {
System.out.println("我是最终通知");
}

//@AfterThrowing("anyMethod()")
@AfterThrowing(pointcut="anyMethod()", throwing="e")
public void doExceptionAdvice(Exception e){
System.out.println("我是例外通知,即异常通知"+ e);
}

//环绕通知可以替代上面的所有通知,完成一个完整的权限拦截的过程
@Around("anyMethod()")
public Object doAroundProfiling(ProceedingJoinPoint pjp) throws Throwable {
//如果我们使用环绕通知,必须要在环绕通知内部执行下面的这个方法
//如果不执行这个方法,那么业务bean中被拦截的方法是不会执行的
//在执行这个方法的时候,如果后面还有其他切面,执行是顺序是这样的:
//先执行后面的切面,如果后面没有切面,再执行最终的目标对象的业务方法,
//如果你不调用这个方法,后面的切面及这个业务bean的方法都不会会执行

Object result = null;
if (true) {
//前置通知
try {
result = pjp.proceed();
//后置通知
} catch (Exception ex) {
// 例外通知
} finally {
//最终通知
}
}
return result;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值