title: SpringBoot來自Swagger的Restful文件生成 tags:
- SpringBoot
- swagger
- restful
- doc categories: springboot date: 2017-11-21 15:13:32
背景
- 基於SpringBoot的方案普遍要做到前後端分離
- 程式碼即文件
- 程式碼變化太快
- 文件經常忘記更改
方案
基於Swagger的方案可以比較簡單的基於restful api做出相關文件
效果
![143805_NQuS_871390.png][]
![143812_tFo3_871390.png][]
點選try it out
可以看到結果如下
![143831_DJEb_871390.png][]
那麼我們需要做什麼呢?
程式碼
- 需要在pom裡面引入swagger
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<properties>
<swagger.version>2.2.2</swagger.version>
</properties>
```
2. 新建swagger的配置類
```java
package com.f6car.base.config;
import com.f6car.base.constant.Constants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author qixiaobo
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("使用Swagger2構建RESTful APIs")
.description("客戶端與服務端介面文件")
.termsOfServiceUrl("http://qixiaobo.site")
.contact("qixiaobo")
.version("1.0.0")
.build();
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage(Constants.CONTROLLER_PACKAGE))
.paths(PathSelectors.any())
.build();
}
}
```
我們僅需要提供基礎web包名即可
3. 超類上增加簡單註釋【沒有也沒關係】
```java
/*
* Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.f6car.base.controller.base;
import com.f6car.base.common.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
/**
* @author qixiaobo
*/
public abstract class AbstractRestController<V extends Vo, S extends So> {
@Autowired
private Service<V, S> service;
@PostMapping()
@ApiOperation(value = "新建實體", notes = "")
public Result add(@RequestBody V vo) {
service.save(vo);
return ResultGenerator.genSuccessResult();
}
@DeleteMapping("/{id}")
@ApiOperation(value = "刪除實體", notes = "")
public Result delete(@PathVariable Serializable id) {
service.deleteById(id);
return ResultGenerator.genSuccessResult();
}
@PutMapping
@ApiOperation(value = "更新實體", notes = "")
public Result update(@RequestBody V vo) {
service.update(vo);
return ResultGenerator.genSuccessResult();
}
@GetMapping
@ApiOperation(value = "獲取實體列表", notes = "")
public Result list(S so) {
PageHelper.startPage(so.getCurrentPage(), so.getPageSize());
List<V> list = service.findAll();
PageInfo pageInfo = new PageInfo(list);
return ResultGenerator.genSuccessResult(pageInfo);
}
@GetMapping("/{id}")
@ApiOperation(value = "獲取單個實體", notes = "")
public Result detail(@PathVariable Serializable id) {
V vo = service.findById(id);
return ResultGenerator.genSuccessResult(vo);
}
@DeleteMapping("/batch")
@ApiOperation(value = "批量刪除實體", notes = "")
public Result batchDelete(@RequestParam String ids) {
service.deleteByIds(ids);
return ResultGenerator.genSuccessResult();
}
@GetMapping("/batch")
@ApiOperation(value = "批量獲取實體", notes = "")
public Result batchDetail(@RequestParam String ids) {
List<V> vos = service.findByIds(ids);
return ResultGenerator.genSuccessResult(vos);
}
@PostMapping("/batch")
@ApiOperation(value = "批量新建實體", notes = "")
public Result add(@RequestBody List<V> vos) {
service.save(vos);
return ResultGenerator.genSuccessResult();
}
}
```
4. webConfig需要增加對html的處理【預設都是spring處理】
```java
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
```
如上就可以簡單的的生成
[143805_NQuS_871390.png]: https://static.oschina.net/uploads/space/2017/1121/143805_NQuS_871390.png
[143812_tFo3_871390.png]: https://static.oschina.net/uploads/space/2017/1121/143812_tFo3_871390.png
[143831_DJEb_871390.png]: https://static.oschina.net/uploads/space/2017/1121/143831_DJEb_871390.png
複製程式碼