簡體   English   中英

Java Spring:如何將注釋封裝在另一個注釋中?

[英]Java Spring : how can I encapsulate annotations within an other annotation?

是否可以將注釋封裝在具有值的其他注釋中?

我的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權限,第一個是映射和方法的名稱,第二個是 class 的名稱。

在此示例中,只有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可以應用於注釋,因此如果您在方法中使用選中的注釋,則可以利用傳遞性。

解決方案的帖子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM