Spring Boot如何让Web API自动生成文档,并解决swagger-annotations的API注解description属性废弃的问题

前后端分离的系统架构中,前端开发人员需要查看后端WEB API的文档来进行开发。采用后端API文档自动生成的方式,可以大幅提高开发效率。swagger是一个被广泛使用的文档自动生成工具,可以与多种编程语言结合使用。我们可以利用合适的jar包,让swqgger来协助java开发。本文讲述了如何把 swagger 与 Spring Boot 框架结合起来使用。

我用一个项目来解释如何完成上述的目标。打开 eclipse。 File → New → Maven Project → 选中Create a simple project(skip archetype selection)和Use default Workspace location → Next → Group Id 填成 zhangchao,Artifact Id 填成 blog4 → Finish。这时我们可以在eclipse中看到一个blog4项目。

当我们完成blog4项目的时候,blog4的目录结构应该如下:

blog4
│
├─ pom.xml
│
└─ src
     │
     └─ main
         │
         ├─ java
         │     └─ zhangchao
         │          │
         │          └─ blog4
         │               │
         │               ├─ Blog4Application.java
         │               ├─ Blog4MvcConfig.java
         │               ├─ User.java
         │               ├─ UserAddressController.java
         │               └─ UserController.java
         │
         └─ resources
              ├─ application.properties
              └─ public
                   ├─ css
                   └─ images

我使用 Maven 来管理项目。 Maven 项目的配置文件 pom.xml 内容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>zhangchaogroupId>
    <artifactId>blog4artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
    properties>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.4.2.RELEASEversion>
        <relativePath/>
    parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>       
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.6.1version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.6.1version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>

pom.xml 文件中 groupId 是 io.springfox 的两个依赖是自动生成文档所需的依赖组件。

java/main/resources下的application.properties 文件内容:

spring.jackson.serialization.indent_output=true
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true

Blog4Application.java 启动项目,代码如下:

package zhangchao.blog4;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Blog4Application {
    public static void main(String[] args){
        SpringApplication.run(Blog4Application.class, args);
    }
}

Blog4MvcConfig.java 是配置类,代码如下:

package zhangchao.blog4;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Blog4MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                .allowCredentials(false).maxAge(3600);
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                /* .tags 第一个参数必须是Tag,后面的是 Tag 类型的可选参数
                 new Tag(String,String) 第一个参数是key,第二个参数是Value。注解@Api#tags传入的是tag的key */
                .tags(new Tag("user", "用户相关"),getTags())
                .select()
                .apis(RequestHandlerSelectors.basePackage("zhangchao.blog4"))
                .paths(PathSelectors.any())
                .build();
    }

    private Tag[] getTags() {
        Tag[] tags = {
            new Tag("book", "书相关的API"),
            new Tag("dog", "狗相关")
        };
        return tags;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("api根地址:http://api.xiaomo.info:8080/")
                .termsOfServiceUrl("https://xiaomo.info/")
                .contact(new Contact("张超","",""))
                .version("1.0")
                .build();
    }
}

Blog4MvcConfig 类中,为了生成文档,必须在类名上方加注解@EnableSwagger2。createRestApi()、getTags() 和 apiInfo() 三个成员方法都是用来配置文档自动生成的。createRestApi 中的 tags 方法参数需要注意,第一个参数必须是 Tag。后面的是可选参数,类型可以是Tag数组,也可以是多个Tag。

传值类 User 的内容:

package zhangchao.blog4;

import java.math.BigDecimal;
import java.sql.Timestamp;

import io.swagger.annotations.ApiModelProperty;

public class User {
    public String id;
    public String name;
    public BigDecimal balance;

    @ApiModelProperty(example="1481770165015")
    public Timestamp birthday;
}

在这里 @ApiModelProperty(example="1481770165015") 用来更改 swagger 的用户界面。用户界面上关于 user 的例子中,birthday 的取值是1481770165015。如果你用传统java bean的形式,在成员变量上直接加这个注解就行,get方法和set方法不做改变。

UserController.java 的内容:

package zhangchao.blog4;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.UUID;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/*
 * 在swagger-annotations jar包中 1.5.X版本以上, 注解 io.swagger.annotations.API 
 * 中的description被废弃了。新的swagger组件中使用了新的方法来对Web api 进行分组。原来使用 description ,
 * 默认一个Controller类中包含的方法构成一 个api分组。现在使用tag,可以更加方便的分组。
 * 比如把两个Controller类里的方法划分成同一个分组。tag的key用来区分不同的分组。tag的value用做分组的描述。
 * @ApiOperation 中value是api的简要说明,在界面api 链接的右侧,少于120个字符。
 * @ApiOperation 中notes是api的详细说明,需要点开api 链接才能看到。
 * @ApiOperation 中 produces 用来标记api返回值的具体类型。这里是json格式,utf8编码。
 */

@RestController
@RequestMapping("/user")
@Api(tags={"user"})
public class UserController {

    @ApiOperation(value = "新增用户", notes = "新增用户注意事项", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value="",method=RequestMethod.POST)
    public User save(@RequestBody User user){
        user.id = UUID.randomUUID().toString();
        return user;
    }

    @ApiOperation(value = "用户详情", notes = "用户详情注意事项", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value="/{id}",method=RequestMethod.GET)
    public User get(@PathVariable String id){
        User user = new User();
        user.balance = new BigDecimal("3.2");
        user.id = id;
        user.name = "小明";
        user.birthday = new Timestamp(System.currentTimeMillis());
        return user;
    }

    @ApiOperation(value = "更新用户", notes = "更新用户注意事项", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value="",method=RequestMethod.PUT)
    public User update(@RequestBody User user){
        return user;
    }

    @ApiOperation(value = "删除用户", notes = "删除用户注意事项", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable String id){
        return "success";
    }
}

UserAddressController.java 内容:

package zhangchao.blog4;


import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/*
UserAddressController 和 UserController 的 Api 注解的 tags 参数都使用
了key=user 的tag。在文档中,可以看到 这两个Controller的web api 被放在同一个
分组中。
*/

@RestController
@RequestMapping("/user")
@Api(tags={"user"})
public class UserAddressController {



    @ApiOperation(value = "用户地址详情", notes = "用户地址详情注意事项", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value="/address/{id}",method=RequestMethod.GET)
    public String get(@PathVariable String id){
        return "莱阳路8号";
    }


    @ApiOperation(value = "删除用户地址", notes = "删除用户地址注意事项", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value="/address/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable String id){
        return "success";
    }
}

从 http://download.csdn.net/detail/zhangchao19890805/9747024

这里下载压缩文件,解压后是一个public 文件夹,这个public文件夹包含css 文件夹和images文件夹。请把这个 public 文件夹放到 src/main/resources 下面。

启动项目,访问 http://localhost:8080/swagger-ui.html 就可以看到文档了。成功后的文档应该如下显示:

Spring Boot如何让Web API自动生成文档,并解决swagger-annotations的API注解description属性废弃的问题_第1张图片

你可能感兴趣的:(SpringBoot)