java - Spring AOP 中如何使用 @Pointcut(?) 拦截被 “特定注解” 注解的类中所有的方法?

查看:2264
本文介绍了java - Spring AOP 中如何使用 @Pointcut(?) 拦截被 “特定注解” 注解的类中所有的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我定义了一个 Log 注解,然后希望被 @Log 注解的类所有方法的执行,都可以被 Spring 的 AOP 拦截到。

Log 注解:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Log {

    String value() default "";
    
}

LogAdvice:

@Aspect
@Component
public class LogAdvice {

    @Pointcut("@target(ssm.annotation.Log)")
    private void advice() {
    }

    @Before("advice()")
    public void doBefore(JoinPoint jp) {
        String methodInfo = getMethodInfo(jp);
        System.out.println(methodInfo);
    }
    
    ...
}

但是部署 Web 程序的时候,控制台报错了,

Spring:INFO CglibAopProxy: Unable to proxy method [protected final void org.springframework.transaction.support.AbstractPlatformTransactionManager.resume(java.lang.Object,org.springframework.transaction.support.AbstractPlatformTransactionManager$SuspendedResourcesHolder) throws org.springframework.transaction.TransactionException] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.

@Pointcut("@target(ssm.annotation.Log)")

改为

@Pointcut("@annotation(ssm.annotation.Log)")

便不会报错,然后在方法上使用 @Log 便可以在 AOP 中拦截到。

请问 @Pointcut(?) 中该如何设置内容,才能实现在类上 @Log,然后该类中所有的方法在执行前都可以被 AOP 拦截到呢?

解决方案

使用 @within("ssm.annotation.Log"),可以拦截被 @Log 注解的类的所有方法。

这篇关于java - Spring AOP 中如何使用 @Pointcut(?) 拦截被 “特定注解” 注解的类中所有的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆