美文网首页
springboo根据目录结构自动生成路由前缀

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

作者: 听城 | 来源:发表于2020-05-01 11:22 被阅读0次

    配置文件中配置api的根目录

    missyou:
      api-package: com.lin.missyou.api
    

    重写getMappingForMethod方法

    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;
    
    
    public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {
    
        @Value("${missyou.api-package}")
        private String apiPackagePath;
    
        @Override
        protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
            RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
            if (mappingInfo != null) {
                String prefix = this.getPrefix(handlerType);
                return RequestMappingInfo.paths(prefix).build().combine(mappingInfo);
            }
            return null;
        }
    
        private String getPrefix(Class<?> handlerType) {
            String packageName = handlerType.getPackage().getName();
            String dotPath = packageName.replaceAll(this.apiPackagePath, "");
            return dotPath.replace(".", "/");
        }
    }
    

    重写MVC注册机制

    import com.lin.missyou.core.hack.AutoPrefixUrlMapping;
    import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
    
    @Configuration
    public class AutoPrefixConfiguration implements WebMvcRegistrations {
    
        @Override
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            return new AutoPrefixUrlMapping();
        }
    }
    

    相关文章

      网友评论

          本文标题:springboo根据目录结构自动生成路由前缀

          本文链接:https://www.haomeiwen.com/subject/awwfghtx.html