用于Spring安全性的SpEL:将值从XML传递到基于Java的SpEL配置
我想将xml文件中指定的属性值传递给Java中的Spring表达式(SpEL)。 你能指出我如何实现这一目标吗? 为清楚起见,我提供了以下示例。
example.xml文件:
请记住,我有’用户’和’客户’模型类。
我希望通过以下方式使用预授权注释和Spring表达式来保护名为“edit”的方法。
@PreAuthorize("(#user.userId == #customer.customerId)") public Boolean edit(User user, Customer custmer) { return true; }
问题是,如何将userId和customerId的值从“example.xml文件传递到上面的表达式来比较这两个值,然后保护’edit’方法?
注意:我不想使用权限评估程序。 如果可以在不考虑许可评估者的情况下进行,请指出我。 非常感谢您的支持与合作!
您可以使用@
引用SpEL表达式中的bean引用 。
我稍微改变了你的例子,以便更清楚地表明SpEL表达式的哪一部分引用了bean,哪部分引用了方法参数。 鉴于以下配置:
仅当User
参数的userId
为33
(这是userBean
的userId
属性的值)时,才允许使用此方法。
@PreAuthorize("#user.userId == @userBean.userId") public Boolean edit(User user, Customer custmer) { return true; }
同样,您可以使用以下内容引用id为customerBean
的Customer(在我的示例XML中定义):
@PreAuthorize("#custmer.userId == @customerBean.userId") public Boolean edit(User user, Customer custmer) { return true; }
如果您希望它对您当前的XML配置执行相同的操作,您可以使用以下内容。 这里的要点是@
之后的值应该与bean的名称匹配。
@PreAuthorize("#user.userId == @user.userId") public Boolean edit(User user, Customer custmer) { return true; }
@Rob,它不起作用。 如果userBean的userId和customerBean的customerId相等,则允许’edit’方法。 根据你的建议,它应该写成如下方式:
@PreAuthorize("@userBean.userId == @customerBean.customerId") public Boolean edit(User user, Customer custmer) { return true; }
但它返回以下错误:
java.lang.IllegalArgumentException: Failed to evaluate expression '(@userBean.userId == @customerBean.customerId)'
有什么建议吗?
UPDATE。 将@ userBean.userId更改为@ user.userId,将@ customerBean.customerId更改为@ customer.customerId
为什么将User和Customer声明为spring bean?