@PreAuthorize with Bean in expression (Spring Boot)

H.R*_*iee 5 spring spring-security spring-boot spelevaluationexception

简单的问题,我@Autowired在控制器中设置了一个 @Service 类。

试图在我的控制器中的一种方法上增加一点安全性。所以为了简单起见,我这样做是为了测试

@PreAuthorize("@myService.helloThere()")
public void someControllerMethod() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

但真的没有成功。在方法调用期间出现异常。

java.lang.IllegalArgumentException:无法评估表达式“@myService.helloThere()”

我在这里遗漏了 EL 的东西吗?

更新

只需添加最后一个由异常引起的

引起:org.springframework.expression.spel.SpelEvaluationException: EL1057E:(pos 1): 没有在上下文中注册的 bean 解析器来解析对 bean 'dummyServiceImpl' 的访问

现在我不明白为什么如果我使用 @Autowired 就不能在 StandardEvaluationContext 中访问它?

更新 2

由于我在自定义GlobalMethodSecurityConfiguration扩展类中连接了自己的角色层次结构,因此默认情况下DefaultMethodSecurityExpressionHandler没有applicationContext设置。我不确定为什么这是设计使然,或者我遗漏了一些明显的东西。我搜索了参考页面并找到了另一个帮助我解决问题的SO 线程。我正在发布更新的安全配置。

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Autowired
    ApplicationContext applicationContext; //added this

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {           
        final DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();

        handler.setApplicationContext(applicationContext); //added this
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();

        roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER_MANAGER > ROLE_USER");
        handler.setRoleHierarchy(roleHierarchy);
        return handler;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*P S 0

尝试这个。

@PreAuthorize("myService.helloThere()")