Springcloud 学习笔记07-Swagger2的详细使用教程


1、Swagger2的功能

Swagger2是一个可以生成项目文档的工具,用来对项目的接口进行描述.是需要简单的配置就可以立马使用,并且还可以在自带的前端界面进行函数的测试.

最核心的作用:编写和维护接口文档。

2、spring boot 集成Swgger2

(1)引入相关的依赖:

<!-- swagger -->
        <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>

        <!--引入ui包-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.3</version>
        </dependency>

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

        <!--增加两个配置解决NumberFormatException-->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.22</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

(2)启动类添加@EnableSwagger2注解

package com.ttbank.flep.file;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableAsync;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication(scanBasePackages="com.ttbank")
@EnableFeignClients
@EnableDiscoveryClient
@EnableSwagger2
@EnableAsync
@MapperScan("com.ttbank.flep.file.mapper")
public class FileApplication {
    public static void main(String[] args) {
        SpringApplication.run(FileApplication.class,args);
    }
}

(3)编写配置类:

package com.ttbank.flep.file.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // api扫包
                .apis(RequestHandlerSelectors.basePackage("com.ttbank.flep.file.controller"))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("Toov5|微服务电商系统").description("demo")
                .termsOfServiceUrl("http://www.itmayiedu.com")
                // .contact(contact)
                .version("1.0").build();
    }

}

(4)访问查看

特别注意:根据application.yml的相关配置,访问对应的网址。

server.servlet.context-path为路径前缀,若yml中有相关设置,必须在url路径中添加前缀。

本案例访问原生swagger2-ui的网址:http://localhost:7003/flep/file/swagger-ui.html

swagger-bootstrap-ui是基于swagger接口api实现的一套UI,因swagger原生ui是上下结构的,在浏览接口时不是很清晰,所以,swagger-bootstrap-ui是基于左右菜单风格的方式,适用与我们在开发后台系统左右结构这种风格类似,方便与接口浏览。

重点推荐swagger-bootstrap-ui的访问方式:

http://127.0.0.1:7003/flep/file/doc.html

#application.yml为基本配置文件
server:
  port: 7003
  servlet:
    context-path: /flep/file  #

swagger-ui效果图为:

swagger-bootstrap-ui效果图:

 3.Swagger2 具体使用案例

首先,介绍Swagger常用注解

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置" @ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明" @ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

 @ApiParam是一个描述方法参数的注解

  注解内的常用属性有

  name:参数名(与请求参数参数名一致)

  value:参数说明

  required:是否必须

  @ApiParam和@ApiImplicitParam类似,都是对方法参数进行标注,但是注解添加的位置不同,@ApiParam添加在方法参数前,@ApiImplicitParam添加在方法前,@ApiImplicitParam拥有dataType和paramType

案例代码如下:

package com.ttbank.flep.file.controller;

import com.ttbank.flep.file.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api("用户信息管理")
@RestController
@RequestMapping("/user/*")
public class UserController {

    private final static List<User> userList = new ArrayList<>();
    
    {
        userList.add(new User(1, "Tom", "A fool cat"));
        userList.add(new User(2, "Jerry", "A clever mouse"));
    }

    @ApiOperation("获取用户列表")
    @GetMapping("list")
    public List userList() {
        return userList;
    }

    @ApiOperation("新增用户")
    @PostMapping("add")
    public boolean add(User user) {
        return userList.add(user);

    }

    @ApiOperation("更新用户")
    @ApiImplicitParam(name = "user", value = "单个用户信息", dataType = "User")
    @PutMapping("update")
    public boolean update(User user) {
        return userList.remove(user) && userList.add(user);
    }

    @ApiOperation("批量删除用户")
    @ApiImplicitParam(name = "users", value = "N个用户信息", dataType = "List<User>")
    @DeleteMapping("delete")
    public boolean delete(@RequestBody List<User> users) {
        return userList.removeAll(users);
    }
}

通过访问http://127.0.0.1:7003/flep/file/doc.html

 

参考文献:https://blog.csdn.net/qq_41291945/article/details/104544417

https://www.cnblogs.com/toov5/p/9974147.html

https://www.cnblogs.com/Shadowplay/p/10606945.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM