SpringBoot根据目录结构自动生成路由前缀的实现代码

网友投稿 720 2022-12-19

SpringBoot根据目录结构自动生成路由前缀的实现代码

SpringBoot根据目录结构自动生成路由前缀的实现代码

目录前言具体实现配置文件指定基础包自动补全路由前缀处理类自动补全路由前缀配置类测试类测试

前言

本文介绍如何根据目录结构给RequestMapping添加路由前缀(覆盖RequestMappingHandlerMapping中的getMappingForMethod方法,修改其中的Url),如下图的实际访问路径为:/v1/test/test。

具体实现

配置文件指定基础包

application.properties

api-package = com.coisini.springbootlearn.controller

自动补全路由前缀处理类

AutoPrefixUrlMapping.java

import org.springframework.beans.factoojczLqsry.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(mappingInojczLqsfo);

}

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

/**

* @DescriptioojczLqsn 自动补全路由前缀配置类

* 通过接口的形式主动发现

* @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";

}

}

测试

目录结构如下

访问结果

目录结构变更

访问结果

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:一篇文章带你了解MySQL数据库基础
下一篇:基于params、@PathVariabl和@RequestParam的用法与区别说明
相关文章

 发表评论

暂时没有评论,来抢沙发吧~