暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SpringBoot - 根据目录结构自动生成路由前缀

咸鱼很咸 2021-08-13
633

点击蓝字 关注我们

前言

本文介绍如何根据目录结构给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";
}

}

测试

  • 目录结构如下

  • 访问结果

  • 目录结构变更

  • 访问结果

END
文章转载自咸鱼很咸,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论