ConditionalOnProperties 不会在具有多个端点 Spring 的 class 引导中切换端点

ConditionalOnProperties does not toggle an endpoint within a class with multiple endpoints Spring Boot

我尝试对具有多个端点的 class 中的特定端点使用 ConditionalOnProperties 注释。但是,条件似乎并没有切换它,而是始终打开。它在 class 级别上运行良好,但在端点级别上效果不佳。这是一个错误吗?

@RequestMapping(path = "/test", consumes = {"application/x-www-form-urlencoded"})
@ResponseBody
@Timed()
@ConditionalOnProperty(name = "test.enabled")
public String test(@RequestParam(EXCEPTION_LOG_MESSAGE) String errorLog) {

据我理解注解,应该是给bean用的。对于 return 是 @Bean 的方法或 class 是 @Component@Sevice 或 – 如您的情况 – @Controller.

您注释的方法没有定义 bean,而只是 bean 的一个方法,它无论如何都会被定义。

为了实现你的目标,你可以例如

  • 将特定端点放到一个额外的 Controller 并注释那个
  • 或使用 @Value 注释获取 属性 并向您的方法添加一个 if 使其 return 类似于 404如果 属性 未设置:

后一个想法的示例:

@Value("${test.enabled}")
private boolean testEnabled;

public ResponseEntity test() {
    if (!testEnabled) {
        return ResponseEntity.notFound().build();
    }
    // ...
}

可能还有更多选择。