JavaSpring:如何将注释封装在其他注释中



是否可以用值将注释封装在其他注释中?

我的API上有很多端点,我想自动化端点访问所需的roles / permissions

这是当前代码:

@RestController
@RequestMapping("/health")
public class HealthController {
@GetMapping("/isAlive")
@PreAuthorize("hasAnyAuthority('ISALIVE', 'HEALTH_ENDPOINT')")
public String isAlive() {
return "Server is up and running";
}
@GetMapping("/hello")
@PreAuthorize("hasAnyAuthority('HELLO', 'HEALTH_ENDPOINT')")
public String hello() {
return "Hello";
}
}

每个端点都有2权限,第一个是映射和方法的名称,第二个是类的名称。

在这个例子中,只有2个不同的端点,这很容易,但最终产品将有数百个,手动执行所有权限将很容易出错,而且效率不高。

这是想要的结果:

@RestController
@RequestMapping("/health")
public class HealthController {
@GetMapping("/isAlive")
@MyAuthorisationAnnotation
public String isAlive() {
return "Server is up and running";
}
@GetMapping("/hello")
@MyAuthorisationAnnotation
public String hello() {
return "Hello";
}
}

其中@MyAuthorisationAnnotation将为@PreAuthorize注释提供正确的参数。

有可能吗?

是否可以将注释封装在其他注释中有价值?

一个注释可以有另一个注释作为成员。

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAuthorizationAnnotation {
PreAuthorize value() default @PreAuthorize("hasAnyAuthority('HELLO', 'HEALTH_ENDPOINT')"); 
}

然而,我认为这没有帮助。我不熟悉Spring,但我认为这篇文章解决了你的问题,因为@PreAuthorize似乎可以应用于注释,所以如果你在方法中使用选中的注释,你可以利用传递性。

解决方案的后

最新更新