你可以定制与路径匹配和处理 URL 有关的选项。关于各个选项的细节,请参见 PathMatchConfigurer javadoc。
下面的例子显示了如何在 Java 配置中自定义路径匹配:
@Configuration@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.setPatternParser(new PathPatternParser())// addPathPrefix:它的功能是,给所有给定注解(如 @RestController)的控制器添加路径前缀,// 比如原始路径是 /demo/hello,添加下面这个配置之后,就必须使用 /api/demo/hello 访问.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));}private PathPatternParser patternParser() {// ...}}
下面是等效的 XML 配置
<mvc:annotation-driven><mvc:path-matchingtrailing-slash="false"path-helper="pathHelper"path-matcher="pathMatcher"/></mvc:annotation-driven><bean id="pathHelper" class="org.example.app.MyPathHelper"/><bean id="pathMatcher" class="org.example.app.MyPathMatcher"/>
