根據目錄結構自動生成路由前綴

根據目錄結構自動生成路由前綴

  • 自定義RequestMappingInfo

    public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {
    
        // 基礎包路徑
        @Value("${api.base.package.path}")
        private String apiBasePackagePath;
    
        @Override
        protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
            RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
            if(mappingInfo != null) {
                String prefixPath = this.getPrefixPath(handlerType);
                // 在原來的requestMapping上加上前綴
                return RequestMappingInfo.paths(prefixPath).build().combine(mappingInfo);
            }
            return null;
        }
    
        // 獲取路由前綴,去掉基礎包路徑後的目錄
        private String getPrefixPath(Class<?> handlerType) {
            String packagePath = handlerType.getPackage().getName();
            return packagePath
                    .replaceAll(apiBasePackagePath, "")
                    .replaceAll("\\.", "/");
        }
    }
    
  • 將自定義的RequestMappingInfo註冊到Spring容器中

    public class AutoPrefixUrlRegister implements WebMvcRegistrations {
    
        @Override
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            return new AutoPrefixUrlMapping();
        }
    }
    
  • 訪問api

    package com.shuguangtj.v1;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping(value = "/hello")
    public class HelloWorldController {
    
        @GetMapping(value = "/say")
        public String say() {
    
            return "hello, world";
        }
    }
    

    在配置文件中設置的基礎包路徑api.base.package.path = com.shuguangtj,所以say()方法的訪問路徑就變成了http://localhost:8080/v1/hello/say,如果把HelloWorld放在了com.shuguangtj.v2包下,訪問路徑自動就變成了http://localhost:8080/v2/hello/say

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章