可以使用属性启用/禁用 spring boot @RestController 吗? [英] Can a spring boot @RestController be enabled/disabled using properties?

查看:43
本文介绍了可以使用属性启用/禁用 spring boot @RestController 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个带有 @RestController 的标准"spring boot 应用程序,例如

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);
    }
}

如果/除非某个应用程序属性存在/不存在,是否有一种注释或技术可以阻止端点启动.

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.

因为配置文件不是属性,通过配置文件控制并不能解决我的问题.

Because a profile is not a property, control via profiles does not solve my problem.

推荐答案

我使用 @ConditionalOnExpression 找到了一个简单的解决方案:

I found a simple solution using @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);
    }
}

加上这个注解,除非我有

With this annotation added, unless I have

my.controller.enabled=true

在我的 application.properties 文件中,控制器根本不会启动.

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.

这篇关于可以使用属性启用/禁用 spring boot @RestController 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆