@RefreshScope与@ConditionalOnProperty不起作用

Maj*_*box 6 runtime environment-variables spring-boot spring-cloud spring-boot-actuator

问题

探索一种@RequestMapping无需重新启动JVM即可按需启用/禁用端点的选项。在运行时在端点上实现kill开关。

尝试

我尝试了以下方法,但@RefreshScope似乎无法使用@ConditionOnProperty

@RestController
@RefreshScope
@ConditionalOnProperty(name = "stackoverflow.endpoints", havingValue = "enabled")
public class MyController {

    @Value("${stackoverflow.endpoints}")
    String value;

    @RequestMapping(path = "/sample", method = RequestMethod.GET)
    public ResponseEntity<String> process() {
        return ResponseEntity.ok(value);
    }

}
Run Code Online (Sandbox Code Playgroud)

使用更新属性

POST /env?stackoverflow.endpoints=anyvalue
Run Code Online (Sandbox Code Playgroud)

并使用重新加载上下文

POST /refresh
Run Code Online (Sandbox Code Playgroud)

此时,控制器返回更新后的值。

还有其他方法可以实现所需的功能吗?

Gri*_*pal 1

Boot 中的条件仅应用于配置类级别或 bean 定义级别。

这可能对你有帮助。

public class MyWebConfiguration extends WebMvcConfigurationSupport {
 @Bean
 @ConditionalOnProperty(prefix="stackoverflow.endpoints",name = "enabled")
 public MyController myController() {
    return new MyController ();
 }
}
Run Code Online (Sandbox Code Playgroud)