java Spring:在属性文件中定义@RequestMapping 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31904444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:20:06  来源:igfitidea点击:

Spring: define @RequestMapping value in a properties file

javaspringspring-mvcannotations

提问by JeanValjean

Is it possible to define the value of a @RequestMappingannotation in Spring by defining it in a properties file?

是否可以@RequestMapping通过在属性文件中定义注释来定义Spring 中注释的值?

Actually, I do something like:

实际上,我做了类似的事情:

@Controller
@RequestMapping("/xxx")
public class MyController {
...
}

But I would like to store the path /xxxin a properties file. Why? For instance, it is less likely that I do mystakes in my templates if I rename the path in the controller.

但我想将路径存储/xxx在属性文件中。为什么?例如,如果我重命名控制器中的路径,我不太可能在我的模板中做 mystakes。

In other framework this is allowed (see Symfony, for instance).

在其他框架中这是允许的(例如,参见 Symfony)。

回答by Bohuslav Burghardt

It should be possible to use placeholders in @RequestMapping, like for example @RequestMapping("${foo.bar}"). Take a look at the documentationfor more details:

应该可以在 中使用占位符@RequestMapping,例如@RequestMapping("${foo.bar}"). 查看文档以获取更多详细信息:

Patterns in @RequestMappingannotations support ${…?} placeholders against local properties and/or system properties and environment variables. This may be useful in cases where the path a controller is mapped to may need to be customized through configuration. For more information on placeholders, see the javadocs of the PropertyPlaceholderConfigurer class.

@RequestMapping注释中的模式支持${…?针对本地属性和/或系统属性和环境变量的 } 占位符。在控制器映射到的路径可能需要通过配置进行自定义的情况下,这可能很有用。有关占位符的更多信息,请参阅 PropertyPlaceholderConfigurer 类的 javadoc。

回答by Paulo

Thx for the help. It is my contribution... No dependencies are necessary because maven do everything by itself.

谢谢你的帮助。这是我的贡献......不需要依赖项,因为 maven 自己做所有事情。

In the property file - use maven interpolation, such as below:

在属性文件中 - 使用 maven 插值,如下所示:

vs= v1

us= users
me= messages

url.user=${vs}/${us}
url.mess=${vs}/${me}

In your destiny file, for example controller/resource (in mycase):

在你的命运文件中,例如控制器/资源(在我的情况下):

@RestController
//@RequestMapping("v1/users") <<<<<<instead this
@RequestMapping("${url.user}")<<<<<<use this
@Api(value = "API RESTFUL)
public class UserResource {
//