Spring AOP 拦截指定注解标识的类或方法

7 篇文章 2 订阅

代码Demo

@Aspect
@Component
@Order(10)
public class BidAuthorityProxy {


    /**
     * 扫描指定包下的类中使用@EnableRoleAuthority注解修饰的类
     */
    @Around("@within(com.core.annotation.EnableRoleAuthority) && within(com.bid..*)")
    public Object verifyRoleExecuteCommand(ProceedingJoinPoint pjp) throws Throwable {
        // 获取当前拦截方法的对象
        MethodSignature msig = (MethodSignature) pjp.getSignature();
        Method targetMethod = pjp.getTarget().getClass().getDeclaredMethod(msig.getName(), msig.getMethod().getParameterTypes());

        // 获取当前方法注解中的值
        VerifyRoleAuthority annotation = targetMethod.getAnnotation(VerifyRoleAuthority.class);

        // 如果类上面没有注解,则获取接口上此方法的注解
        if (annotation == null) {
            Class<?>[] inters = pjp.getTarget().getClass().getInterfaces();
            for (Class<?> inter : inters) {
                Method targetInterMethod = inter.getDeclaredMethod(msig.getName(), msig.getMethod().getParameterTypes());
                annotation = targetInterMethod.getAnnotation(VerifyRoleAuthority.class);
                if (annotation != null) {
                    break;
                }
            }
        }

        // 获取到注解中的值后进行后续自定义逻辑操作

        return pjp.proceed();// 执行方法
    }

}

相关说明:

AOP中扫描指定注解相关说明
(1)@annotation:用来拦截所有被某个注解修饰的方法
(2)@within:用来拦截所有被某个注解修饰的类
(3)within:用来指定扫描的包的范围

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值