swagger使用入门

Swagger-概述

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger让部署管理和使用功能强大的API从未如此简单。

本篇将使用SpringBoot进行搭建Swagger

1. maven导入Swagger包

<dependencies>
        <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>
</dependencies>

2. 配置开启swagger2

新建一个配置类,然后开启使用@EnableSwagger2注解就可以了
注:在后续的操作中都是在swagger配置类中进行

@Configuration      /*配置类*/
@EnableSwagger2     /*开启swagger自动配置*/
public class swaggerConfig {

}

3. 测试swagger

在此之前可以编写一个测试的Controller,效果更佳显著

@Controller
public class swaggerController {

    @RequestMapping(path = "/hello")
    @ResponseBody
    public String hello(){
        return "hello swagger";
    }

}

启动项目进行访问swagger:http://localhost:8080/swagger-ui.html

能够看到此页面代表swagger基础配置就完成了,swagger页面分为4个内容

  1. swagger信息:相当于作者的个人信息(可自行修改)
  2. 接口信息:在controller中编写的接口全在里面(SpringBoot默认有个接口就是error)
  3. 开发者组:是一个下拉框,可以创建不同的开发者信息(比如某些业务的接口是01开发的,某些接口是02开发的)

在这里插入图片描述

4. 配置swagger信息

swagger信息:开发者名称、个人网站地址、邮箱地址、描述信息…(可以根据不同的Docket获取不同的ApiInfo中Contact的name属性来区别接口的开发者)

@Configuration       /*配置类*/
@EnableSwagger2     /*开启swagger自动配置*/
public class swaggerConfig {

    /*配置swagger的Docket实例*/
    @Bean
    public Docket getDocket( ){
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }

    /*配置swagger 信息==ApiInfo*/
    private ApiInfo apiInfo( ) {
        /*作者信息*/
        Contact contact = new Contact("阿波","https://libo2000.github.io/","[email protected]");
        return new ApiInfo(
                "阿波的SwaggerAPI文档",
                "记忆之中没有辛苦,只有遗憾",
                "v1.0",
                "https://libo2000.github.io/",
                contact,
                "Apache2.0",
                "https://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>()
        );
    }

}

修改完之后再次访问:http://localhost:8080/swagger-ui.html 明显的看到swagger信息与之前发生了变化
在这里插入图片描述

5. 配置swagger扫描接口

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

     /*设置需要显示的swagger环境*/
     Profiles profiles =Profiles.of("dev","test");
      /**/
     boolean flag = environment.acceptsProfiles(profiles);

   return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .groupName("阿波") //swagger信息(ApiInfo)中的name成员变量(不同的开发者信息就需要设置多个ApiInfo在不同的Docket实例中获取)
        /*.enable(false):是否启用swagger  如果为false,浏览器中不能访问(默认为true)*/
        .enable(flag)
        .select()
        /*RequestHandlerSelectors:配置扫描接口的方式
               * basePackage:指定扫描的包
               * any:扫描全部
               * none:不扫描
               * withClassAnnotation:扫描类上的注解,参数为一个注解的反射对象
               * withMethodAnnotation:扫描方法上的注解*/
        .apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
        /*paths():过滤路径*/
//      .paths(PathSelectors.ant("/action"))
        .build();
 }

这里有个问题:这么才能控制swagger的显示问题,Docket实例中enable()默认为true就是说可以访问(false则不能访问),但是我想让swagger在测试阶段才可以访问,其他时候不能访问,如何实现?

方便我们测试所以创建多个SpringBoot的配置文件properties,在主配置文件中配置spring.profiles.active=具体配置环境(代表当前项目使用的是那一个项目环境)

  1. 设置需要显示的swagger环境(例如:只有在dev或者test环境下才显示):Profiles profiles =Profiles.of(“dev”,“test”);
  2. 判断当前环境是否为设置的环境(返回boolean值true或false):boolean flag = environment.acceptsProfiles(profiles);
  3. 将flag变量传到Docket实例的.enable(flag)属性中:enable(flag)

至此就可以通过获取当前环境而控制swagger的访问

在这里插入图片描述
在这里插入图片描述

6. swagger分组与接口注释

swagger分组:

在swagger配置时可分为不同的多个Docket对象,相当于每一个Docket对象就是一个项目中的开发者。可以设置多个ApiInfo信息,再通过Docket的groupName()参数为ApiInfo中Contact对象的name成员变量,在上面我们知道了Docket中可以设置扫描接口,那我们在通过扫描不同的接口、配置不同的ApiInfo信息,那么就可以进行swagger的分组(就可以在swagger中区别不同开发者写的接口及代码)

@Configuration           /*配置类*/
@EnableSwagger2     /*开启swagger自动配置*/
public class swaggerConfig {

    @Bean
    public Docket getDocket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("阿波2");
    }

    @Bean
    public Docket getDocket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("阿波3");
    }

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

        /*设置需要显示的swagger环境*/
        Profiles profiles =Profiles.of("dev","test");
        /**/
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("阿波") //swagger信息(ApiInfo)中的name成员变量(不同的开发者信息就需要设置多个ApiInfo在不同的Docket实例中获取)
                /*.enable(false):是否启用swagger  如果为false,浏览器中不能访问(默认为true)*/
                .enable(flag)
                .select()
                /*RequestHandlerSelectors:配置扫描接口的方式
                        * basePackage:指定扫描的包
                        * any:扫描全部
                        * none:不扫描
                        * withClassAnnotation:扫描类上的注解,参数为一个注解的反射对象
                        * withMethodAnnotation:扫描方法上的注解*/
                .apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
                /*paths():过滤路径*/
//                .paths(PathSelectors.ant("/action"))
                .build();
    }


    /*配置swagger 信息==ApiInfo*/
    private ApiInfo apiInfo() {
        /*作者信息*/
        Contact contact = new Contact("阿波","https://libo2000.github.io/","[email protected]");
        return new ApiInfo(
                "阿波的SwaggerAPI文档",
                "记忆之中没有辛苦,只有遗憾",
                "v1.0",
                "https://libo2000.github.io/",
                contact,
                "Apache2.0",
                "https://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>()
        );
    }
    
}

在这里插入图片描述

swagger常用注解
在swagger如何去描述实体类呢?(JavaBean)

首先创建实体类,然后对实体类及成员变量通过注解进行描述:

@ApiModel("用户实体类")
public class User {

    @ApiModelProperty("用户名")
    public String username;
    
    @ApiModelProperty("密码")
    public String password;
    
}

然后在Controller中进行接口配置:

@RestController
public class swaggerController {

    @GetMapping(path = "/hello")
    public String hello(){
        return "hello swagger";
    }

    /*在接口中,返回值中存在实体类,他就会被扫描到swagger中*/
    @PostMapping(path = "/user")
    public User user(){
        return new User();
    }
    
 }   

在这里插入图片描述
对接口的描述:

    @ApiOperation("user控制类")
    @GetMapping(path = "/hello2")
    public String hello2(@ApiParam("用户名") String username, @ApiParam("密码")String password){
            return username+password;
    }

在这里插入图片描述

Swagger常用注解
在Java类中添加Swagger的注解即可生成Swagger接口,常用Swagger注解如下:

  1. @Api:修饰整个类,描述Controller的作用
  2. @ApiOperation:描述一个类的一个方法,或者说一个接口
  3. @ApiParam:单个参数描述
  4. @ApiModel:用对象来接收参数
  5. @ApiModelProperty:用对象接收参数时,描述对象的一个字段
  6. @ApiResponse:HTTP响应其中1个描述
  7. @ApiResponses:HTTP响应整体描述
  8. @ApiIgnore:使用该注解忽略这个API
  9. @ApiError:发生错误返回的信息
  10. @ApiImplicitParam:一个请求参数
  11. @ApiImplicitParams:多个请求参数

猜你喜欢

转载自blog.csdn.net/weixin_45377770/article/details/106891162
今日推荐