> For the complete documentation index, see [llms.txt](https://spring-boot.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spring-boot.shujuwajue.com/sheng-hua/8spring-bootji-cheng-swagger.md).

# 8.Spring Boot集成Swagger

## 一、Swagger 是什么？

Swagger 是一个规范和完整的框架，用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。\
<http://swagger.io/>\
Springfox 的前身是 swagger-springmvc，是一个开源的 API doc 框架，可以将我们的 Controller 的方法以文档的形式展现，基于 Swagger。\
<http://springfox.github.io/springfox/>

## 二、添加依赖jar

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

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
```

所涉及的文件

![](/files/-LfnTI67bO1vWLpAhFgA)

## 三、配置类

util/configuration/Swagger2Configuration.java

```java
package com.shuju.test2.util.configuration;

import static springfox.documentation.builders.PathSelectors.regex;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * SwaggerConfig
 */
@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    /**
     *
     * @return
     */
    @Bean
    public Docket accessToken() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("api")// 定义组
                .select() // 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.basePackage("com.shuju.test2.controller")) // 拦截的包路径
                .paths(regex("/api/.*"))// 拦截的接口路径
                .build() // 创建
                .apiInfo(apiInfo()); // 配置说明
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()//
                .title("Demo")// 标题
                .description("Api 項目")// 描述
                .termsOfServiceUrl("http://www.shujuwajue.com")//
                .contact(new Contact("revin", "http://www.shujuwajue.com", "509129@qq.com"))// 联系
                //.license("Apache License Version 2.0")// 开源协议
                //.licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")// 地址
                .version("1.0")// 版本
                .build();
    }
}
```

<http://localhost:8080/swagger-ui.html>

## 五、自定义(注解的使用)

* @ApiIgnore

忽略暴露的 api

* @ApiOperation(value = "查找", notes = "根据用户 ID 查找用户")

添加说明

**其他注解：**

* @Api：用在类上，说明该类的作用
* @ApiImplicitParams：用在方法上包含一组参数说明
* @ApiResponses：用于表示一组响应
* @ApiResponse：用在@ApiResponses 中，一般用于表达一个错误的响应信息
* code：数字，例如 400
* message：信息，例如"请求参数没填好"
* response：抛出异常的类
* @ApiModel：描述一个 Model 的信息（这种一般用在 post 创建的时候，使用@RequestBody 这样的场景，请求参数无法使用@ApiImplicitParam 注解进行描述的时候）
* @ApiModelProperty：描述一个 model 的属性（加在entity实体类的属性上）

**更多请查看**

<https://github.com/swagger-api/swagger-core/wiki/Annotations>

附上之前的ApiController参考

```java
package com.shuju.test2.controller;

import java.util.Date;
import java.util.HashMap;

import com.shuju.test2.bean.DemoUserLog;
import com.shuju.test2.cache.DemoUserLogCache;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private DemoUserLogCache demoUserLogCache;

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    @ApiOperation(value = "查找", notes = "根据用户ID查找用户")
    public DemoUserLog get(@RequestParam(defaultValue = "1") Integer id) {
        return demoUserLogCache.selectById(id);
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public DemoUserLog update(@RequestParam(defaultValue = "1") Integer id) {
        DemoUserLog bean = demoUserLogCache.selectById(id);
        bean.setUserName("测试222");
        bean.setCreateTime(new Date());
        demoUserLogCache.updateById(bean);
        return bean;
    }

    @ApiIgnore
    @RequestMapping(value = "/del", method = RequestMethod.GET)
    public String del(@RequestParam(defaultValue = "1") Integer id) {
        return demoUserLogCache.deleteById(id);
    }
}
```

![](/files/-LfnTI6G6Lss1Q2M_A2M)


---

# 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://spring-boot.shujuwajue.com/sheng-hua/8spring-bootji-cheng-swagger.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.
