文章目錄
Spring Boot 2.X - Spring Boot整合Swagger2(starter方式)
上一篇 Spring Boot 2.X - Spring Boot整合Swagger2 我們介紹了Swagger2和Spring Boot 2之間的整合,雖然功能強大,但也是寫了很多重複的代碼。這一章,我們使用SpringForAll社區提供的一個swagger-starter進行整合,一切都變得很簡單了。這裏感謝spring4all社區。
引入依賴
修改上一章項目的pom文件,去掉swagger和swagger-ui依賴,添加swagger-starter依賴,完整依賴如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xudc</groupId>
<artifactId>spring-boot-v2-swagger2-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-v2-swagger2-starter</name>
<description>Demo project for Spring Boot Swagger2 Starter</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter -->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
添加@EnableSwagger2Doc註解
在主啓動類上添加@EnableSwagger2Doc
註解,開啓swagger功能:
package com.xudc.swagger;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author xudc
*/
@SpringBootApplication
@EnableSwagger2Doc
public class SpringBootSwaggerStarterApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSwaggerStarterApplication.class, args);
}
}
創建實體類
package com.xudc.swagger.pojo;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author xudc
* @date 2019/4/18 15:07
*/
@Data
@Accessors(chain = true)
public class User {
private Integer id;
private String name;
private Integer age;
}
創建Controller對外接口
創建Controller對外接口用於測試
package com.xudc.swagger.controller;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xudc.swagger.pojo.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @author xudc
* @date 2019/4/18 15:06
*/
@RestController
@RequestMapping("/user")
public class UserController {
private static Map<Integer, User> userMap = Maps.newConcurrentMap();
private final static String SUCCESS = "success";
@ApiOperation("獲取用戶列表")
@GetMapping("")
public List<User> list(){
return Lists.newArrayList(userMap.values());
}
@ApiOperation(value = "創建用戶",notes = "根據User對象創建用戶")
@ApiImplicitParam(name = "user",value = "用戶實體json",required = true,dataType = "User")
@PostMapping("")
public String save(@RequestBody User user) {
userMap.put(user.getId(), user);
return SUCCESS;
}
@ApiOperation(value = "查詢用戶",notes = "根據id查找用戶")
@ApiImplicitParam(name = "id", value = "用戶id", required = true, dataType = "int")
@GetMapping("/{id}")
public User find(@PathVariable Integer id){
User user = userMap.get(id);
return user;
}
@ApiOperation(value = "刪除用戶",notes = "根據id刪除指定用戶")
@ApiImplicitParam(name = "id", value = "用戶id", required = true, dataType = "int")
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id) {
userMap.remove(id);
return SUCCESS;
}
@ApiOperation(value = "修改用戶",notes = "根據id修改用戶信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶id", required = true, dataType = "int"),
@ApiImplicitParam(name = "user", value = "用戶實體json", required = true, dataType = "User")
})
@PutMapping("/{id}")
public String update(@RequestBody User user, @PathVariable Integer id){
User u = userMap.get(id);
u.setName(user.getName()).setAge(user.getAge());
userMap.put(id, u);
return SUCCESS;
}
}
接口文檔測試
- POST
Curl
Request URLcurl -X POST "http://localhost:8080/user" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"age\": 12, \"id\": 1, \"name\": \"Cindy\"}"
Response bodyhttp://localhost:8080/user
Response headerssuccess
content-length: 7 content-type: text/plain;charset=UTF-8 date: Sat, 20 Apr 2019 14:01:13 GMT
- GET
Curl
Request URLcurl -X GET "http://localhost:8080/user/1" -H "accept: */*"
Response bodyhttp://localhost:8080/user/1
Response headers{ "id": 1, "name": "Cindy", "age": 12 }
content-type: application/json;charset=UTF-8 date: Sat, 20 Apr 2019 14:01:30 GMT transfer-encoding: chunked
- DELETE
Curl
Request URLcurl -X DELETE "http://localhost:8080/user/1" -H "accept: */*"
Response bodyhttp://localhost:8080/user/1
Response headerssuccess
content-length: 7 content-type: text/plain;charset=UTF-8 date: Sat, 20 Apr 2019 14:19:27 GMT
參數配置
參數示例
swagger.enabled=true
swagger.title=spring-boot-starter-swagger
swagger.description=Starter for swagger 2.x
swagger.version=1.4.0.RELEASE
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=didi
swagger.contact.url=http://blog.didispace.com
[email protected]
swagger.base-package=com.didispace
swagger.base-path=/**
swagger.exclude-path=/error, /ops/**
swagger.globalOperationParameters[0].name=name one
swagger.globalOperationParameters[0].description=some description one
swagger.globalOperationParameters[0].modelRef=string
swagger.globalOperationParameters[0].parameterType=header
swagger.globalOperationParameters[0].required=true
swagger.globalOperationParameters[1].name=name two
swagger.globalOperationParameters[1].description=some description two
swagger.globalOperationParameters[1].modelRef=string
swagger.globalOperationParameters[1].parameterType=body
swagger.globalOperationParameters[1].required=false
// 取消使用默認預定義的響應消息,並使用自定義響應消息
swagger.apply-default-response-messages=false
swagger.global-response-message.get[0].code=401
swagger.global-response-message.get[0].message=401get
swagger.global-response-message.get[1].code=500
swagger.global-response-message.get[1].message=500get
swagger.global-response-message.get[1].modelRef=ERROR
swagger.global-response-message.post[0].code=500
swagger.global-response-message.post[0].message=500post
swagger.global-response-message.post[0].modelRef=ERROR
默認的配置
- swagger.enabled=是否啓用swagger,默認:true
- swagger.title=標題
- swagger.description=描述
- swagger.version=版本
- swagger.license=許可證
- swagger.licenseUrl=許可證URL
- swagger.termsOfServiceUrl=服務條款URL
- swagger.contact.name=維護人
- swagger.contact.url=維護人URL
- swagger.contact.email=維護人email
- swagger.base-package=swagger掃描的基礎包,默認:全掃描
- swagger.base-path=需要處理的基礎URL規則,默認:/**
- swagger.exclude-path=需要排除的URL規則,默認:空
- swagger.host=文檔的host信息,默認:空
- swagger.globalOperationParameters[0].name=參數名
- swagger.globalOperationParameters[0].description=描述信息
- swagger.globalOperationParameters[0].modelRef=指定參數類型
- swagger.globalOperationParameters[0].parameterType=指定參數存放位置,可選header,query,path,body.form
- swagger.globalOperationParameters[0].required=指定參數是否必傳,true,false
項目地址
完整代碼:Github