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

Spring: define @RequestMapping value in a properties file

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

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

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

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

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

应该可以在 @RequestMapping 中使用占位符,例如 @RequestMapping("${foo.bar}")。查看 documentation 了解更多详情:

Patterns in @RequestMapping annotations 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.

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

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

vs= v1

us= users
me= messages

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

在你的命运文件中,例如controller/resource(在我的例子中):

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

正如 bohuslav burghardt 提到的,这是完全可能的。

因此,如果您的 application.properties 文件中存储了一个公共域,您可以使用占位符在 controller/s 中调用它,甚至可以将占位符和文本链接在一起。

例如...
在您的 .properties 文件中

app.domain = mydomain/v1

在控制器中

@RestController
@RequestMapping("${app.domain}/my-controller")
public class MyController {