> For the complete documentation index, see [llms.txt](https://taocares.gitbook.io/development-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://taocares.gitbook.io/development-guide/kai-fa-zhi-nan/swagger-ji-cheng.md).

# Swagger集成

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

{% hint style="info" %}
使用的Swagger版本是2.X，但是由于2.X版本的注解配置变化较大，因此使用Swagger 1.5.X版本的注解，详细参考请见本节最后的链接。
{% endhint %}

## 依赖

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

## 配置

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

{% code title="DemoApplication.java" %}

```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);
    }
}
```

{% endcode %}

## 接口定义

接口类使用`@Api`，接口方法使用`@ApiOperation`，接口参数使用`@ApiParam`。

{% code title="FooController.java" %}

```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);
        }
    }
}
```

{% endcode %}

## 对象定义

接口涉及的数据模型（如：DTO/VO等），需要使用Swagger提供的注解进行描述。

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

{% code title="FooDto.java" %}

```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;
}
```

{% endcode %}

## 查看定义

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

## 参考文档

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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://taocares.gitbook.io/development-guide/kai-fa-zhi-nan/swagger-ji-cheng.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
