我有很多方法都需要对此注释进行注释:
@Override
@PostAuthorize("hasPermission(returnObject.id, 'mypackage.SecuredClazz', 'ADMINISTRATION')")
public MyObject findSectionAById(SomeId id) {
////the code
}
注解更加复杂,它包括hasRole
和不同的hasPermission
条件。许多对象正在实现mypackage.SecuredClazz
并具有ID。结果,我在同一正文中有很多复制粘贴批注:
@PostAuthorize("hasPermission(returnObject.id, 'mypackage.SecuredClazz', 'ADMINISTRATION')")
是否有可能使用其他注释或其他方式不将整行复制到100个方法中?
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@PostAuthorize("hasPermission(returnObject.id, 'mypackage.SecuredClazz', 'ADMINISTRATION')"
public @interface SecuredClazzAuthorized { }
用法:
@Override @SecuredClazzAuthorized public MyObject findSectionAById(SomeId id) { ... }
方法安全性元注释
您可以使用元注释来确保方法的安全性,以使代码更具可读性。如果发现在整个代码库中重复相同的复杂表达式,这将特别方便。例如,考虑以下内容:
@PreAuthorize("#contact.name == authentication.name")
而不是在所有位置重复此操作,我们可以创建一个可以用作替代的元注释。
@Retention(RetentionPolicy.RUNTIME) @PreAuthorize("#contact.name == authentication.name") public @interface ContactPermission {}
元注释可用于任何Spring Security方法安全注释。为了保持符合规范,JSR-250注释不支持元注释。