加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

spring AOP之重用切点表达式

发布时间:2020-12-15 01:13:12 所属栏目:大数据 来源:网络整理
导读:在使用@Before(execution(value=""))使用切点时,如果是需要重复使用,可以进行统一的设置。 比如说现在有这么一个前置通知和后置通知: package com.gong.spring.aop.impl;import java.util.Arrays;import java.util.List;import javax.management.RuntimeE

在使用@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(")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读