是否可以执行以下操作:
public void doStuff(@RequirePrivilege("foo") User user) {
// ...
}
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代码,它被注释以便在特定方法之前或之后执行。我想做反向并注释应该更改的代码。
最终我可以在方法中进行上述检查,但是注释的处理方式提供了额外的文档,这使得用户显然需要特定的权限,而不必使文档与代码保持同步。
答案 0 :(得分:1)
我确信您的“权限不足”示例可以使用Spring AOP来完成,因为这就是Spring Security的工作方式。你可以通过建议和AspectJ做一些非常复杂的事情。
答案 1 :(得分:1)
您可以使用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.