Springboot AOP 如何做可配置话切点

AOP系列文章
AOP 的动态匹配和静态匹配

Springboot 可以定义注解切点去拦截注解修饰的类方法以及execution (xxxx)切点去拦截具体的类方法。默认情况下我们都会使用注解@PointCut去定义切点,然后定义切面拦截切点。但有些场景需要我们在配置文件(.properties/yml)中配置execution 灵活的去修改需要拦截的切点。这样我们可以将一些公共的拦截增强放到jar包推送到仓库中共享。

通用不可动态配置的做法

@Aspect
@Component
public class TransactionConfig {

    private static final String C_POINT_CUT = "execution(public * com.allens.export.service.*.*(..))";

    @Pointcut(C_POINT_CUT)
    public void pointCut () {};

    //@Pointcut("execution(public * com.allens.export.service.*.*(..))")
    //public void pointCut () {};

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        System.out.println("----------------");
    }

    @Around("pointCut()")
    public Object process (ProceedingJoinPoint joinPoint) throws Throwable {
        return joinPoint.proceed();
    }

    @After("pointCut()")
    public void after(JoinPoint joinPoint) {

    }
}

可以看到我们可以将切点写成static final 传入到注解中,但我们并不能传变量到切点中。解下来就要讲重点部分,如何动态配置切点。其实我们可以猜到,AOP原理就是使用Java动态代理或CGlib进行增强代理。我们使用注解@PointCut定义切点其实也是需要代码去解析然后增强。我们其实也可以直接写代码去增强我们的类,手动定义切点,手动定义切面等等。

动态配置切点

AspectJExpressionPointcut提供表达式匹配类和方法。

public class GreetingDynamicPointcut extends AspectJExpressionPointcut {
}

MethodInterceptor 提供拦截方法的能力,我们可以借助它实现注解@Around功能

@Slf4j
public class GreetingInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        try {
            log.info("调用前...");
            return methodInvocation.proceed();
        } catch (Exception e) {
            log.error("error", e);
            throw e;
        } finally {
            log.info("调用后...");
        }
    }
}

GreetingAdvice 这个类继承了GreetingInterceptor可以实现@Around环绕功能,继承了AfterReturningAdvice实现了@After方法调用后拦截功能,继承了MethodBeforeAdvice实现了方法调用前的拦截功能。

@Slf4j
public class GreetingAdvice extends GreetingInterceptor implements MethodBeforeAdvice, AfterReturningAdvice, AdvisorAdapter {

    @Override
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        // 输出切点
        System.out.println("Pointcut:" + target.getClass().getName() + "."
                + method.getName());
        if (args.length > 0) {
            String clientName = (String) args[0];
            System.out.println("How are you " + clientName + " ?");
        }
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(returnValue);
    }

    @Override
    public boolean supportsAdvice(Advice advice) {
        return true;
    }

    @Override
    public MethodInterceptor getInterceptor(Advisor advisor) {
        return null;
    }
}

配置

@Configuration
public class WebmvcConfig {

    @Bean
    public Pointcut customPointCut() {
        GreetingDynamicPointcut greetingDynamicPointcut = new GreetingDynamicPointcut();
        // ① 
        greetingDynamicPointcut.setExpression("execution(public * com.allens.test.controller..*(..)) || execution(public * com.allens.test.service..*(..))");
        return greetingDynamicPointcut;
    }

    @Bean
    GreetingBeforeAdvice getAdvice () {
        return new GreetingBeforeAdvice();
    }

	// ②
    @Bean
    DefaultPointcutAdvisor defaultPointcutAdvisor () {
        DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor();
        defaultPointcutAdvisor.setPointcut(customPointCut());
        defaultPointcutAdvisor.setAdvice(getAdvice());
        return defaultPointcutAdvisor;
    }
}

① 我们实现动态配置只需要把这里的execution 字符串替换成自己从配置文件中获取的配置即可。

② 自定义切面,可以灵活配置切点和切面。

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
Spring Boot AOP(面向切面编程)是Spring框架的一个重要特性,它允许开发者将横切关注点(例如日志记录、事务管理等)与主要业务逻辑进行分离。通过AOP,开发者可以在程序运行时将这些关注点动态地织入到目标对象中。 在Spring Boot中使用AOP可以通过以下步骤实现: 1. 添加依赖:在pom.xml文件中添加Spring AOP的依赖。例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 2. 创建切面类:创建一个带有切面逻辑的类,并使用`@Aspect`注解标记。切面类中定义的方法称为切点,并使用`@Pointcut`注解进行定义。例如: ```java @Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.demo.service.*.*(..))") public void serviceMethods() {} @Before("serviceMethods()") public void beforeAdvice() { System.out.println("Before advice executed."); } @After("serviceMethods()") public void afterAdvice() { System.out.println("After advice executed."); } } ``` 3. 配置AOP:在配置类中启用AOP,并将切面类添加到容器中。例如: ```java @Configuration @EnableAspectJAutoProxy public class AopConfig { // 将切面类添加到容器中 @Bean public LoggingAspect loggingAspect() { return new LoggingAspect(); } } ``` 现在,当调用带有`com.example.demo.service`包下的方法时,AOP将会在方法执行之前和之后执行相应的切面逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

澄风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值