SpringBoot根据目录结构自动生成路由前缀的实现代码
作者:Maggieq8324
本文介绍如何根据目录结构给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
*/
@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 - 根据目录结构自动生成路由前缀的文章就介绍到这了,更多相关SpringBoot目录结构路由前缀内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- SpringBoot如何使用MyBatisPlus逆向工程自动生成代码
- SpringBoot集成Mybatis-plus并实现自动生成相关文件的示例代码
- Springboot Mybatis Plus自动生成工具类详解代码
- SpringBoot项目使用mybatis-plus逆向自动生成全套代码
- SpringBoot整合Mybatis Generator自动生成代码
- springboot整合freemarker代码自动生成器
- SpringBoot整合screw实现数据库文档自动生成的示例代码
- springboot 通过代码自动生成pid的方法
- SpringBoot+MyBatis-Plus+Velocity实现代码自动生成
