簡體   English   中英

有沒有辦法在 Spring Boot 中通過屬性啟用/禁用注釋?

[英]Is there any way to enable/disable a annotation by property in Spring Boot?

我有一些屬性文件,例如:

應用程序.properties

enable.test.controller=true
enable.cross.origin=false

我想根據配置文件啟用/禁用某些功能。 例如,我有一個 controller 只在特定環境中打開:

@Controller(enable=${enable.test.controller})
public class TestController() {

}

而且我還想啟用/禁用注釋@CrossOrigin屬性

@Controller
@CrossOrigin(enable=${enable.cross.origin})
public class TestController2() {

}

有什么方法可以使@Annotation(enable=${property})起作用嗎?

任何建議將不勝感激!

  1. 您可以將@ConditionalOnProperty添加到 controller 並根據該控制器的 bean 是否初始化來指定屬性。
@ConditionalOnProperty(name = "enable.test.controller", havingValue = "true")
  1. 而對於@CrossOrigin ,如果要給單個controller加上這個注解,可以在注解中指定origins屬性,指定允許的origin URLs。

或者

您可以創建全局 CORS 配置,可以使用配置文件輕松關閉或打開該配置。 例如。 @Profile("CORS_enabled_profile")

    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:8080");
            }
        };
    }

暫無
暫無

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

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