Swagger集成

基于HTTP的Webservice相比于基于SOAP协议的Webservice一大缺点就是缺少约束和文档定义,因此我们需要采用Swagger完成对接口的定义,以及相关代码生成等。

依赖

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

配置

开发者需要在入口类上配置@EnableSwagger2启用Swagger的支持。

DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@EnableDiscoveryClient
public class DemoApplication {

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

接口定义

接口类使用@Api,接口方法使用@ApiOperation,接口参数使用@ApiParam

FooController.java
package com.example.demo.controller;

import com.example.demo.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/foos")
@Api("Foo CRUD服务")
public class FooController {

    @Autowired
    private FooService fooService;

    @GetMapping("/all")
    @ApiOperation("根据条件不分页查询结果")
    public List<FooDto> findAll(FooQo fooQo) {
        return fooService.findAll(fooQo);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询结果")
    public FooDto findById(@ApiParam("业务主键") @PathVariable("id") Long id) {
        Optional<FooDto> optional = fooService.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            throw new ResourceNotFoundException("Foo", id);
        }
    }
}

对象定义

接口涉及的数据模型(如:DTO/VO等),需要使用Swagger提供的注解进行描述。

数据模型使用@ApiModel,字段使用@ApiModelProperty,推荐对于数据模型中的字段使用example属性配置示例值。

FooDto.java
package com.example.demo.dto;

import com.taocares.commons.beans.annotation.Mapping;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel("Foo数据传输对象")
public class FooDto {

    @ApiModelProperty(value = "唯一标识", example = "1")
    private Long id;

    @ApiModelProperty(value = "名字", example = "张三")
    private String name;

    @ApiModelProperty(value = "时间", example = "2018-10-01")
    @Mapping(datePattern = "yyyy-MM-dd")
    private String date;
}

查看定义

配置springfox-swagger-ui的依赖之后,接口文档会随项目启动自动生成。路径为当前应用路径下的/swagger-ui.html,如:http://localhost:8080/swagger-ui.html#/

参考文档

详细的注解以及参数说明:https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X

Last updated