本文介绍如何根据目录结构给RequestMapping添加路由前缀,具体实现方法,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
前言
本文介绍如何根据目录结构给RequestMapping添加路由前缀(覆盖RequestMappingHandlerMapping中的getMappingForMethod方法,修改其中的Url),如下图的实际访问路径为:/v1/test/test。
具体实现
配置文件指定基础包
application.properties
api-package = com.coisini.springbootlearn.controller
自动补全路由前缀处理类
AutoPrefixUrlMapping.java
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import java.lang.reflect.Method; import java.util.Objects; /** * @Description 自动补全路由前缀处理类 * RequestMappingHandlerMapping 负责处理标注了@RequestMapping的控制器 * @author coisini * @date Aug 10, 2021 * @Version 1.0 */ public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping { /** * 读取基础包配置 */ @Value("${api-package}") private String bathApiPackagePath; /** * 重写方法路由获取 * @param method * @param handlerType * @return */ @Override protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType); if (Objects.nonNull(mappingInfo)) { String prefix = this.getPrefix(handlerType); /** * RequestMappingInfo.paths(prefix).build() 根据前缀生成mappingInfo * combine(mappingInfo) 拼接原来的mappingInfo */ return RequestMappingInfo.paths(prefix).build().combine(mappingInfo); } return mappingInfo; } /** * 获取方法路由前缀 * @param handleType * @return */ private String getPrefix(Class handleType) { String packageName = handleType.getPackage().getName(); String dotPath = packageName.replace(this.bathApiPackagePath, "").replace(".","/"); return dotPath; } }
自动补全路由前缀配置类
AutoPrefixConfiguration.java
/** * @Description 自动补全路由前缀配置类 * 通过接口的形式主动发现 * @author coisini * @date Aug 10, 2021 * @Version 1.0 */<b style="color:transparent">来源gao@!dai!ma.com搞$$代^@码!网</b> @Component public class AutoPrefixConfiguration implements WebMvcRegistrations { @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new AutoPrefixUrlMapping(); } }
测试类
@RestController @RequestMapping("/test") public class TestController { @GetMapping(value = "/test") public String test(){ return "hello"; } }
测试
目录结构如下
访问结果
目录结构变更
访问结果
以上就是SpringBoot根据目录结构自动生成路由前缀的实现代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!