是否可以执行以下操作: <代码>

<代码>
public void doStuff(@RequirePrivilege("foo") User user) {
    // ...
}

<代码>

让它有效地运行,好像它是以下? <代码>

<代码>
public void doStuff(User user) {
    if(!user.hasPrivilege("foo"))
        throw new UserHasInsufficientPrivileges(); // this is a RuntimeException
    // ...
}

<代码>

我知道Spring有各种各样的AOP支持,但我能找到的最好的是AOP代码,它被注释以便在特定方法之前或之后执行。我想做反向并注释应该更改的代码。

最终我可以在方法中进行上述检查,但是注释的处理方式提供了额外的文档,这使得用户显然需要特定的权限,而不必使文档与代码保持同步。

有帮助吗?

解决方案

您可以使用AspectJ来执行此操作,因为它将与注释匹配。然后,您可以使用around方面来确定用户是否满足使用此方法的要求。

Spring允许你使用AspectJ,我建议如果可能的话你不能在运行时这样做,但是在编译时,因为没有理由为你启动应用程序时使用这个方面付出代价。但是,如果你必须在运行时这样做,那么这是可行的,对我来说,我尽量使用编译时。

您可能需要查看AspectJ In Action( http://www.manning.com/laddad2/ )但是这里有一个例子: 签名模式:

* *(@RequestParam
(@Sensitive *))

描述

*Any method with one parameter marked with the @RequestParam annotations and the parameter’s type is marked with the @Sensitive annotation.*

实施例

void create(@RequestParam
MedicalRecord mr), assuming
MedicalRecord carries the
@Sensitive annotation.

其他提示

我确定你的“特权不足”。示例可以使用 Spring AOP 来完成,因为那是Spring Security如何工作。你可以通过建议和AspectJ做一些非常复杂的事情。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top