swagger简单使用

我只希望swagger在生产环境中使用,在发布的时候不使用

  • 判断是不是生产环境 flag=false

  • 注入enable(flag)

    @Configuration
    @EnableSwagger2 //开启swagger2
    public class SwaggerConfig {

    //配置swagger的Docket的bean实例
    @Bean
    public Docket docket(Environment environment) {

    //配置要显示的swagger环境
    Profiles profiles = Profiles.of("dev", "test");
    //通过environment.acceptsProfiles判断是否处在自己设定的环境中
    boolean flag = environment.acceptsProfiles(profiles);

    return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo())
    .enable(flag)//enable是否开启swagger,如果为false,则swagger不能在浏览器中访问
    .select()
    //RequestHandlerSelectors,配置要扫描接口的方式
    //basePackage:指定要扫描的包
    //any():扫描全部
    //none():不扫描
    //withClassAnnotation:扫描类上的注解
    //withMethodAnnotation:扫描方法的注解
    .apis(RequestHandlerSelectors.basePackage("com.sss.swaggerdemo.controller"))
    //过滤什么路径
    .paths(PathSelectors.ant("/sss/**"))
    .build();
    }

    private ApiInfo apiInfo() {
    //作者信息
    Contact contact = new Contact("cyhh", "https://www.cnblogs.com/cyhl/#/c/subject/category/default.html",
    "1554791452@qq.com");
    return new ApiInfo(
    "Swagger Api 文档",
    "只是山野笨拙,我也笨拙",
    "1.0",
    "https://www.cnblogs.com/cyhl/#/c/subject/category/default.html",
    contact,
    "Apache 2.0",
    "http://www.apache.org/licenses/LICENSE-2.0",
    new ArrayList());

    }
    }

配置Api文档的分组

.groupName("ch")

如何配置多个分组,多个Docket实例即可

@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}

posted @ 2021-09-01 11:08  青歌与  阅读(92)  评论(0)    收藏  举报