Spring Boot 集成swagger实例

时间:2022-11-19 08:43:22

原文:https://github.com/x113773/testall/issues/5

1. 首先添加maven依赖
```
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
```

2. 编写swagger配置[SwaggerConfig.java](https://github.com/x113773/testall/blob/master/src/main/java/com/ansel/testall/swagger/SwaggerController.java)

```
@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")// base,最终调用接口后会和paths拼接在一起
.select()
.paths(or(regex("/api/.*")))//过滤的接口
.build()
.apiInfo(testApiInfo());
}

private ApiInfo testApiInfo() {
return new ApiInfoBuilder()
.title("大标题大标题大标题")//大标题
.description("详细描述详细描述")//详细描述
.version("1.0版本版本")//版本
.termsOfServiceUrl("NO terms of service")
.contact("/作者/作者/作者 ")//作者
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}

}
```

3. 测试用的控制器[SwaggerController.java](https://github.com/x113773/testall/blob/master/src/main/java/com/ansel/testall/swagger/SwaggerController.java)
```
@RestController
public class SwaggerController {

@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public Error400 getUser(@PathVariable Long id) {
Error400 er = new Error400();
return er;
}

@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对", response = Error400.class) })
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value = "/api/user", method = RequestMethod.POST)
public String postUser(@RequestBody User user) {
return "success";
}

}
```

4. 实体类[Error400.java](https://github.com/x113773/testall/blob/master/src/main/java/com/ansel/testall/swagger/Error400.java) 和 [User.java](https://github.com/x113773/testall/blob/master/src/main/java/com/ansel/testall/swagger/User.java)
```
@ApiModel(value = "400Error")
public class Error400 {
/**
* 错误反馈编码
*/
@ApiModelProperty(value = "错误反馈编码")
private String respCode;

/**
* 错误反馈描述
*/
@ApiModelProperty(value = "错误反馈描述")
private String respDesc;

//省略get set

}
```

启动项目,访问http://localhost:8080/swagger-ui.htmlSpring Boot 集成swagger实例