Spring aop的通知 配置bean的方式

  1. 前置通知。
  2. 后置通知,出现异常也执行。
  3. 返回通知,出现异常不执行。
  4. 异常通知。
  5. 环绕通知。

配置bean的方式举例子: 只写切面日志类,前置 + 后置通知。
需要两个注解:

import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    /**
     * 在 ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码
     */
    @Before("execution(* demo.aop.ArithmeticCalculator.*(..))")
    private void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("the method: " + methodName +  " begins width: " + Arrays.asList(args));
    }

    @After("execution(* demo.aop.ArithmeticCalculator.*(..))")
    private void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("the method: " + methodName +  " ends.");
    }
}

重用切入点表达式:

@Aspect
@Component
public class LoggingAspect {

    /**
     * 定义一个方法,用于声明切入点表达式,一般的,该方法中不需要添加其它代码
     */
    @Pointcut("execution(* demo.aop.ArithmeticCalculator.*(..))")
    public void pointCutExpression() {
    }

    /**
     * 在 ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码
     */
    @Before("pointCutExpression()")
    private void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("the method: " + methodName + " begins width: " + Arrays.asList(args));
    }

    @After("pointCutExpression()")
    private void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("the method: " + methodName + " ends.");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值