如何在Spring Boot控制器的@RequestMapping中读取application.properties的context-path
嗨,我来帮你搞定这个需求!在Spring Boot里把配置文件中的context-path注入到控制器的@RequestMapping里,有几种简单易行的方法,我给你一步步说明:
方法一:直接在@RequestMapping中使用配置占位符
这是最直接的方式,Spring支持在@RequestMapping的value属性里用${配置项}的占位符语法,自动读取application.properties里的配置值并拼接路径。
示例代码:
@RestController // 直接用${server.context-path}读取配置,和/auth拼接 @RequestMapping("${server.context-path}/auth") public class AuthController extends BaseController { // 你的接口方法写在这里 }
你只需要确保application.properties里的配置正确:
server.port=8080 server.context-path=/SekcjaN
注意:如果你的Spring Boot版本是2.x及以上,配置项已经改成了
server.servlet.context-path=/SekcjaN,记得对应修改配置文件哦!
方法二:结合@Value注入配置(需在代码中使用该值时)
如果你不仅要在@RequestMapping里用,还需要在控制器的方法或逻辑中使用context-path的值,可以先用@Value把配置注入到变量中,同时@RequestMapping依然用占位符:
@RestController @RequestMapping("${server.context-path}/auth") public class AuthController extends BaseController { // 注入context-path到变量中,方便代码里使用 @Value("${server.context-path}") private String contextPath; @GetMapping("/demo") public String getDemo() { // 比如在这里使用contextPath变量 return "当前应用的上下文路径是:" + contextPath; } }
这样既满足了@RequestMapping的路径需求,又能在代码里随时调用这个配置值。
额外提示
如果你的项目中有多个控制器都需要加上这个context-path前缀,也可以通过配置全局的RequestMapping前缀来统一设置,不用每个控制器都写一遍。比如实现WebMvcConfigurer接口,重写configurePathMatch方法:
@Configuration public class WebConfig implements WebMvcConfigurer { @Value("${server.context-path}") private String contextPath; @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix(contextPath, c -> c.isAnnotationPresent(RestController.class)); } }
这样所有标注了@RestController的控制器都会自动加上这个contextPath前缀,你只需要在控制器的@RequestMapping里写/auth就可以了~
内容的提问来源于stack exchange,提问作者maciejka

