有什么方法可以在 Spring 引导中通过 属性 enable/disable 注释吗?

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

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

application.properties

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

我想enable/disable一些基于配置文件的功能。例如,我有一个只在特定环境中打开的控制器:

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

}

而且我也想enable/disable注解@CrossOrigin属性

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

}

有什么方法可以让 @Annotation(enable=${property}) 工作吗?

如有任何建议,我们将不胜感激!

  1. 您可以将 @ConditionalOnProperty 添加到您的控制器并指定 属性 基于哪个控制器的 bean 进行初始化。
@ConditionalOnProperty(name = "enable.test.controller", havingValue = "true")
  1. 而对于@CrossOrigin,如果要将此注解添加到单个控制器,可以在注解中指定origins属性并指定允许的源URL。

您可以创建全局 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");
            }
        };
    }