【问题标题】:Using a String variable in RequestMapping value在 RequestMapping 值中使用字符串变量
【发布时间】:2020-11-07 11:31:18
【问题描述】:

我有以下几点:

@Value("${apiVersion")
private String apiVersion;

@RequestMapping(value = "/{apiVersion}/service/call", method = RequestMethod.POST)

我希望 URL 是:

/apiVersion/service/call

但事实证明{foo} 接受任何值,它实际上并不使用字符串。

有没有办法让我使用字符串值作为 URL 的一部分?

编辑

问题是我有多个电话表明我们重视这一点。

@RequestMapping(value = apiVersion + "/call1", method = RequestMethod.POST)

@RequestMapping(value = apiVersion + "/call2", method = RequestMethod.POST)

@RequestMapping(value = apiVersion + "/call3", method = RequestMethod.POST)

etc.

从技术上讲,我可以按照您的建议为每个常量声明常量,但这听起来并不理想。如果没有办法,那也没关系,我只是想知道有没有。

解决方案

向控制器添加通用映射。

@RequestMapping("${apiVersion}")

【问题讨论】:

    标签: java spring spring-boot api request-mapping


    【解决方案1】:

    如果你只是想在 Java 中预定义路径,就这样做

    @RequestMapping(value = foo + "/service/call", method = RequestMethod.POST)
    

    SpringMvc 中的 PathVariables 旨在作为端点的占位符,如下所示

    @GetMapping(value = "/books/{id}")
    public String displayBook(@PathVariable id) { ... }
    

    【讨论】:

    • 我之前尝试过,但我收到element value must be a constant expression 错误。
    • 然后将其定义为类中的最终静态路径: private static final String FOO_PATH = "foo/service/call";之后您可以在 @RequestMapping(value = FOO_PATH) 中使用它
    • 编辑了我的问题以解决您的想法。
    【解决方案2】:

    如果要将其应用于控制器中的所有方法,请在控制器类级别声明它:

    @RestController
    @RequestMapping("/test")
    public class MyController { ...
    

    并且您不需要在方法路径之前添加它。

    否则它应该是恒定的,比如:

    private static final String FOO = "test";
    

    并在方法路径之前添加它,例如:

    FOO + "/service/call"
    

    【讨论】:

    • 我正在从application.properties 文件中读取值,我还能像您建议的那样使用它吗?我编辑了我的问题以显示实际的声明。
    • 恐怕不幸的是没有。注释中的所有值都必须是常量并在编译时定义。我见过一些在运行时编辑注释的复杂东西,但我一直在做的项目不使用 app.props 而是一个包含这些路径的 java 常量的文件。在 app.props 之外的另一个文件中也不应该是一个问题。
    • @RequestMapping("${apiVersion}") 这确实有效。
    • 好的,我学到了一些新东西:) 似乎 Spring 可以在运行时翻译那个占位符,很好,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2019-06-03
    相关资源
    最近更新 更多