前言
- 如果需要给某个项目整体添加一个请求路径前缀,可以使用
server.servlet.context-path
这个属性去配置 - 有的时候,需要添加请求前缀,来区分前台和后台接口,但是接口都是在同一个 项目里面。这种情况下,可以将前台接口放在web包(如:com.zzhua.controller.web),后台接口放到admin包(如:com.zzhua.controller.admin),然后分别为web包和admin包 指定不同的请求访问前缀。
代码
WebConfig
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
AntPathMatcher antPathMatcher = new AntPathMatcher(".");
configurer.addPathPrefix("/admin-api", clazz-> {
try {
MetadataReader mdr = new CachingMetadataReaderFactory().getMetadataReader(clazz.getName());
if (mdr.getAnnotationMetadata().isAnnotated(Controller.class.getName()) && antPathMatcher.match("**.controller.admin.**", clazz.getPackage().getName())) {
return true;
}
} catch (IOException e) {
}
return false;
});
configurer.addPathPrefix("/web-api", clazz-> {
try {
MetadataReader mdr = new CachingMetadataReaderFactory().getMetadataReader(clazz.getName());
if (mdr.getAnnotationMetadata().isAnnotated(Controller.class.getName()) && antPathMatcher.match("**.controller.web.**", clazz.getPackage().getName())) {
return true;
}
} catch (IOException e) {
}
return false;
});
}
}
TestController
package com.zzhua.controller.web; // 包名,所在包
@RestController
@RequestMapping("test")
public class TestController {
@GetMapping("test01")
public String test01() {
return "ok";
}
}
测试
如果要访问在 com.zzhua.controller.web
(满足设置的条件:**.controller.web.**
)这个包下的TestController#test01
这个接口,需要添加上/web-api
作为前缀,即:http://localhost:8085/web-api/test/test01