前言

本文介紹如何根據目錄結構給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 -



夢想是鹹魚
關注一下吧