前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring AOP之重用切点表达式

spring AOP之重用切点表达式

作者头像
西西嘛呦
发布2020-08-26 10:28:32
2640
发布2020-08-26 10:28:32
举报

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

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

代码语言:javascript
复制
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))")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println(methodName+" begin with "+args);
    }
    //后置通知:在目标方法执行后,无论是否发生异常,执行的通知
    //在后置通知中不能访问目标的执行结果
    @After("execution(public int com.gong.spring.aop.impl.Calculator.*(int, int))")
    public void afterMethod(JoinPoint joinPoint) {
        //获取名字
        String methodName = joinPoint.getSignature().getName();
        //获取参数
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println(methodName+" end with "+args);
    }
}

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

在LoggingAspect 类中新建:

代码语言:javascript
复制
    @Pointcut("execution(public int com.gong.spring.aop.impl.Calculator.*(int, int))")
    public void declarJoinPointExpression() {}

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

代码语言:javascript
复制
@Before("declarJoinPointExpression()")
@After("declarJoinPointExpression()")
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档