Swagger

什么是Swagger

一句话,世界上最流行的Api框架

Swagger的优点

1.Api文档与Api定义实时同步更新
2.可以在线测试Api接口
3.支持多种编程语言

Springboot集成Swagger

1.导入依赖

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

2.测试环境,编写一个HelloController(省略...)

3.集成Swagger

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

}

4.测试访问 http://localhost:8080/swagger-ui.html

5.配置Swagger的apiInfo信息(介绍,作者信息,版本等等...)

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

    //配置Swagger的bean实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    //配置Swagger的apiInfo信息
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("yuu","https://www.cnblogs.com/yuu123/","2675458669@qq.com");
        return new ApiInfo("yuu的SwaggerAPI文档",
                "tomorrow is another day",
                "v1.0",
                "https://www.cnblogs.com/yuu123/",
                contact,
                "Apache 2.0",
                "https://www.baidu.com/",
                new ArrayList()
        );
    }
}

6.环境不同时,设置swagger-ui界面是否可以访问
Swagger
指定2套环境的端口号分别为8081和8082

    //配置Swagger的bean实例
    @Bean
    public Docket docket(Environment e){
        //设置环境
        Profiles profiles = Profiles.of("dev");

        //获取项目环境,判断是否处在自己设定的环境中
        boolean flag = e.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //true可以访问swagger-ui页面,false则不可以
                .enable(flag)
                .select()
                //基于包扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.yuu.swagger.controller"))
                //基于上面指定的包,扫描这个包下的 /swagger/** 请求
                .paths(PathSelectors.ant("/swagger/**"))
                .build();
    }
上一篇:springboot -- swagger2 使用示例


下一篇:DMP助力RTB精准定位 无数据不精准