核心代码如下:

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Function;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class SwaggerConfig {


    // 定义分隔符,配置Swagger多包
    private static final String splitor = ";";


    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //.apis(RequestHandlerSelectors.basePackage("com.dayu.app.controller"))
//                .apis(RequestHandlerSelectors.basePackage("com.dayu.clientweb.controller"))
                .apis(basePackage("com.dayu.app.controller"+splitor+"com.dayu.clientweb.controller"))
                .paths(PathSelectors.any())
                .build();
    }




    /**
     * 重写basePackage方法,使能够实现多包访问,复制贴上去
     * @author  teavamc
     * @date 2019/1/26
     * @return com.google.common.base.Predicate<springfox.documentation.RequestHandler>
     */
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }


    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }


    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }


    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("客户端接口")
                .description("powered by dayu")
                //.termsOfServiceUrl("http://swagger-ui.html/")
                //.contact(contact)
                .version("1.0")
                .build();
    }


}

注意事项

  • 配置多包扫描的时候,请先确保Application 中@ComponentScan扫描到了这个包路径才行。

标签: Swagger配置多包API接口扫描


Reseller Web Hosting

添加新评论

免责声明
本博客部分内容来自于互联网,不代表作者的观点和立场,如若侵犯到您的权益,请联系238611804@139.com。我们会在24小时内进行删除。