可以使用属性启用/禁用弹簧启动@RestController吗? [英] Can a spring boot @RestController be enabled/disabled using properties?
问题描述
给定一个带有 @RestController
的标准弹簧启动应用程序,例如
Given a "standard" spring boot application with a @RestController
, eg
@RestController
@RequestMapping(value = "foo", produces = "application/json;charset=UTF-8")
public class MyController {
@RequestMapping(value = "bar")
public ResponseEntity<String> bar(
return new ResponseEntity<>("Hello world", HttpStatus.OK);
}
}
是否存在注释或技术,如果/除非某个应用程序属性存在/不存在,则阻止端点 at all 。
Is there an annotation or technique that prevents the endpoint from starting at all if/unless a certain application property exists/doesn't exist.
注意:测试方法内的属性并且爆炸不是解决方案,因为端点将存在。
Note: Testing a property inside the method and exploding is not a solution, because the endpoint will exist.
我不知道关心粒度:即启用/禁用一个方法或整个类都很好。
I don't care about the granularity: ie enabling/disabling just a method or the whole class are both fine.
因为a配置文件不是属性,通过配置文件控制不能解决我的问题。
Because a profile is not a property, control via profiles does not solve my problem.
推荐答案
我找到了一个使用<$ c $的简单解决方案c> @ConditionalOnExpression :
@RestController
@ConditionalOnExpression("${my.controller.enabled:false}")
@RequestMapping(value = "foo", produces = "application/json;charset=UTF-8")
public class MyController {
@RequestMapping(value = "bar")
public ResponseEntity<String> bar(
return new ResponseEntity<>("Hello world", HttpStatus.OK);
}
}
添加此注释,除非我有
my.controller.enabled=true
,控制器根本不会启动。
in my application.properties
file, the controller won't start at all.
您也可以使用更方便的方式:
You can also use the more convenient:
@ConditionalOnProperty("my.property")
其行为如上;如果该属性存在且true
,组件将启动,否则不会。
Which behaves exactly as above; if the property is present and "true"
, the component starts, otherwise it doesn't.
这篇关于可以使用属性启用/禁用弹簧启动@RestController吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!