aop的术语理解

1.使用注解方式的aop需要开启注解功能

因为我们使用的是注解方式的AOP,所以要开启注解AOP功能 

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

2.aop的一些术语及对应的注解

切面:就是我们的增强类,比如我们的LogUtil.

@Aspect注解

连接点:就是我们的增强类在哪里执行。

通知:就是我们需要在连接点上增强的方法,比如before,after,around

切点:就是真正被aop增强的连接点。

@Before("execution(* cn.yang.service..*.*(..))")

切点表达式

execution:第一个*表示返回值类型,后面的两个..表示service下的所有类以及子包的内容,如果是一个点就单是service下的内容,括号中的..表示任意入参

within:只能匹配到类这一级

3.注意

要不通过名字获取对象,要不需要接口的类型获取实现类,不能获取接口的实现类

4.通知的执行顺序

1、正常执行:@Before--->@After--->@AfterReturning

2、异常执行:@Before--->@After--->@AfterThrowing

5.在通知中获取切入点的信息

在通知中传入JoinPoint作为参数

@Before("execution(* cn.yang.service.impl.*.*(..))")
public void before(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    Object[] args = joinPoint.getArgs();
    System.out.println(methodName+"方法运行,参数是:"+ Arrays.asList(args));
}

在返回通知中获取返回结果

@AfterReturning(value = "execution(* cn.yang.service.impl.*.*(..))",returning = "returnValue")
public void afterReturning(JoinPoint joinPoint,Object returnValue){
    System.out.println("后置返回通知");
    System.out.println("返回结果为:"+returnValue);
}

注解中需要添加returning,returning的结果就是返回结果的名字,比如说代码中的returnValue

在异常通知中获取异常,注解中添加throwing获取

@AfterThrowing(value = "execution(* cn.yang.service.impl.*.*(..))",throwing = "ex")
public void afterThrowing(JoinPoint joinPoint,Exception ex){
    StringWriter sw =new StringWriter();
    ex.printStackTrace(new PrintWriter(sw,true));
    System.out.println("后置异常通知:"+sw.getBuffer().toString());
}

这基本也是追踪后置异常的固定写法

也可以采用生命切点的方式让通知引用

@Pointcut("execution(* cn.yang.service.impl.*.*(..))")
public void pointCut(){

}

@Before("pointCut()")
public void before(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    Object[] args = joinPoint.getArgs();
    System.out.println(methodName+"方法运行,参数是:"+ Arrays.asList(args));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值