我在 @Query 中使用 Spring Security 表达式,就像这个例子:
@Query("select o from Pet o where o.owner.name like ?#{hasRole('ROLE_ADMIN') ? '%' : principal.username}")
如果您具有 ADMIN 角色,查询将返回所有宠物。但是,如果您没有此角色,则查询仅返回所有者名称与用户身份验证名称相同的 Pet 对象。
这工作正常,但是当我尝试使用 hasAnyRole('ROLE_ADMIN','ROLE_OWNER') 时,系统返回异常...
org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 0): Method call: Method hasAnyRole(java.lang.String,java.lang.String) cannot be found on java.lang.Object[] type
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMetho
...
在 SecurityExpressionRoot 中定义了 hasAnyRole 方法:
public final boolean hasAnyRole(String... roles) {
return hasAnyAuthorityName(defaultRolePrefix, roles);
}
最佳答案
我有同样的问题,快速解决方法是编写 hasRole('ROLE_SUPER') 或 hasRole('ROLE_OWNER')
。
这个异常是由 Spring Data 引起的,据我在调试时所见,它无法解析 SpEL 中参数数量可变的方法。
ExtensionAwareEvaluationContextProvider
方法解析器与 hasAnyRole(String[])
不匹配。
我创建了 https://jira.spring.io/browse/DATACMNS-1518 .
编辑:这个问题已经解决,我刚刚测试了最新的快照并让 hasAnyRole
工作。
关于java - 如何在 @Query 中使用 hasAnyRole 之类的表达式 SpEl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486538/