SpringBoot全局设置请求路径增加前缀
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
在Spring Boot中,可以通过实现WebMvcConfigurer
接口的configurePathMatch
方法来为所有的请求路径添加一个前缀。以下是一个简单的示例代码:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api", c -> true);
}
}
在这个配置中,所有的请求路径将会被添加一个/api
前缀。例如,如果你有一个请求映射@GetMapping("/hello")
,在添加了前缀之后,它将变成@GetMapping("/api/hello")
。
这个配置类需要被Spring Boot应用扫描并加载,通常放在主应用类所在的同一个包或者子包中。如果你使用Java配置,确保@Configuration
注解已经添加到你的主应用类上。
请注意,这种方式添加的前缀只影响Spring MVC的请求映射,不会影响其他非Spring MVC的请求处理,例如过滤器、监听器等。
评论已关闭