0
点赞
收藏
分享

微信扫一扫

AspectJ-基于注解的实现-切入点的定义

NicoalsNC 2022-06-24 阅读 63

切入点的定义

减少切入点定义的冗余

package com.hk.spring.annotation;

import org.aspectj.lang.JoinPoint;
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;

/**
* 定义一个简单的POJO类作为切面类
* @author 浪丶荡
* @param <throwing>
*
*/
@Aspect //表示当前类为切面类
public class MyAspect<throwing> {

/**
* 前置通知
*/
@Before("doFirstPointCat()") //表示前置通知的切入点表达式
public void before(){
System.out.println("前置方法");
}
/**
* 前置通知2
*/
@Before("doThirdPointCat()")
public void before(JoinPoint jp){//jp为切入点表达式值
System.out.println("前置方法执行 "+jp);
}
/**
* 后置通知
*/
@AfterReturning("pointCat()")
public void afterReturing(JoinPoint jp){//jp为切入点表达式值
System.out.println("后置方法执行 "+jp);
}
/**
* 后置通知2
*/
@AfterReturning(value="doThirdPointCat()",returning="result")
public void afterReturing(String result){
System.out.println("后置方法执行 result="+result);
}
/**
* 环绕通知
*/
@Around(value="doThirdPointCat()")
public String around(ProceedingJoinPoint p){
Object result = null;
System.out.println("目标方法执行前");
try {
//执行目标方法
result = p.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("目标方法执行后");

return ((String) result).toLowerCase();

}
/**
* 异常通知
*/
@AfterThrowing(value="pointCat()",throwing="ex")
public void afterThrowing(Exception ex){
System.out.println("afterThrowing执行,异常是:"+ex.getMessage());
}
/**
* 最终通知
*/
@After("pointCat()")
public void after(){
System.out.println("最终通知方法");
}
/**
* 定义切入点,以上execution(* *..ISomeService.doSecond(..))都可以用doSecondPointCat()来代替了
*/
@Pointcut("execution(* *..ISomeService.doSecond(..))")
public void doSecondPointCat(){

}
@Pointcut("execution(* *..ISomeService.doThird(..))")
public void doThirdPointCat(){

}
@Pointcut("execution(* *..ISomeService.doFirst(..))")
public void doFirstPointCat(){

}
}


举报

相关推荐

0 条评论