springboot 根据目录结构生成路由前缀

需求:制定一个目录为“根目录”,从这个目录开始以下的子目录都加入到路由中

例子:如下目录结构,要访问banner中的list接口,要达到目的 /api/v1/open/banner/list

cn.wangningbo.mall
    api
        v1
            admin
            portal
            open
                BannerController.java
    service
    MallApplication.java
@RestController
@RequestMapping("/banner")
public class BannerController{

    @GetMapping("/list")
    public List authorizationRedirectUrl() {
    }
}

实现步骤

mall:
  # 路由生成包路径
  api-package: cn.wangningbo.mall.api
/**
 * 自定义 RequestMappingHandlerMapping
 * @author wangningbo
 */
public class AutoPrefixUrMapping extends RequestMappingHandlerMapping {

    @Value("${mall.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 mappingInfo;
    }

    /**
     * 获取路由前缀
     *
     * @param handlerType
     * @return
     */
    private String getPrefix(Class handlerType) {
        String packageName = handlerType.getPackageName();
        String doPath = packageName.replaceAll(this.apiPackagePath, "");
        return doPath.replace(".", "/");
    }
}
/**
 * 纳入容器管理,让WebMvcRegistrations使用自定义的AutoPrefixUrMapping
 * @author wangningbo
 */
@Component
public class AutoPrefixConfiguration implements WebMvcRegistrations {
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new AutoPrefixUrMapping();
    }
}

你可能感兴趣的:(springboot 根据目录结构生成路由前缀)