You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.3自定义@RequiresAnyRole注解无法访问#root.annotation求助

自定义权限注解的SpEL表达式参数获取问题

需求目标

我想要创建自定义注解,替代以下标准权限校验方式:

@RequiresAnyRole({"UPDATE_DATA"})
@PreAuthorize("hasAnyAuthority('UPDATE_DATA')")

实现后可构建业务级安全注解,并支持方法级权限覆盖。当前使用Spring Boot 3.3版本,自定义注解代码如下:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("@securityHelper.hasAnyListedAuthority(authentication, #root.annotation.value)")
public @interface RequiresAnyRole {
    String[] value() default {};
}

运行报错

使用上述注解时,抛出EL表达式解析错误:

EL1008E: Property or field 'annotation' cannot be found on object of type 'org.springframework.security.access.expression.method.MethodSecurityExpressionRoot' - maybe not public or not valid?"}

尝试的失败方案

GitLab Duo提供的替代方案因使用this同样失败,对应的SpEL表达式如下:

@PreAuthorize("@securityHelper.hasAnyListedAuthority(authentication, T(org.springframework.security.access.expression.method.MethodSecurityExpressionRoot).this.returnObject.getClass().getMethod(T(org.springframework.security.access.expression.method.MethodSecurityExpressionRoot).this.filterObject).getAnnotation(T(com.barclays.spone.loans.security.annotation.RequiresAnyRole)).value())")

校验工具方法

权限校验的工具方法实现如下:

public boolean hasAnyListedAuthority(Authentication auth, String[] authorities) {
    Set<String> userAuthorities = AuthorityUtils.authorityListToSet(auth.getAuthorities());
    return Arrays.stream(authorities)
            .anyMatch(userAuthorities::contains);
}

问题

如何正确获取自定义注解的参数并传入SpEL表达式中?

内容的提问来源于stack exchange,提问作者Leos Literak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:46:12