spring AOP之重用切点表达式

前端之家收集整理的这篇文章主要介绍了spring AOP之重用切点表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在使用@Before(execution(value=""))使用切点时,如果是需要重复使用,可以进行统一的设置。

比如说现在有这么一个前置通知和后置通知

package com.gong.spring.aop.impl;

import java.util.Arrays;
import java.util.List;

import javax.management.RuntimeErrorException;

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.springframework.stereotype.Component;

//把这个类声明为一个切面:需要把该类放入到IOC容器中,再声明为一个切面
@Aspect
@Component
public class LoggingAspect {
    声明该方法为一个前置通知,在目标方法之前执行
    @Before("execution(public int com.gong.spring.aop.impl.Calculator.*(int,int))")
    void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println(methodName+ begin with "+args);
    }
    后置通知:在目标方法执行后,无论是否发生异常,执行的通知
    在后置通知中不能访问目标的执行结果
    @After( afterMethod(JoinPoint joinPoint) {
        获取名字
        String methodName = joinPoint.getSignature().getName();
        获取参数
        List<Object> args = end with args);
    }
}

在@before里面的切点是一样的,我们可以将重复的用切点表达式表示。

在LoggingAspect 类中新建:

    @Pointcut(void declarJoinPointExpression() {}

然后在使用Before等注解时,就可以简化了:

@Before(declarJoinPointExpression())
@After(")

猜你在找的Spring相关文章