文章目錄
Swagger會自動根據我們的接口來生成一個html頁面,在這個頁面上我們可以看到所有接口信息,信息中包含了有哪些參數,每個參數代表什么意思,如果是一個帶body體的請求,還會自動幫我們生成json格式的body。並且還可以像http請求工具那樣進行接口請求.極大的方便了我們編寫接口文檔。
作用:
- 接口的文檔在線生成
- 接口功能測試,替代postman
1. 如何使用
1.1 引入依賴
注意版本,經常會有些意想不到的問題。2.2.2也是比較常用的版本
<!--swagger的依賴start-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<!--swagger的依賴end-->
1.2 創建swagger2配置類
@Configuration
@EnableSwagger2
public class Swagger2Config {
//swagger2的配置文件,這里可以配置swagger2的一些基本的內容,比如掃描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//為當前包路徑
.apis(RequestHandlerSelectors.basePackage("com.jun.cloud"))
.paths(PathSelectors.any())
.build();
}
//構建 api文檔的詳細信息函數
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁面標題
.title("Spring Boot 測試使用 Swagger2 構建RESTful API")
//創建人
.contact(new Contact("余生君", "https://blog.csdn.net/java_collect", ""))
//版本號
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
本例采用指定掃描的包路徑來定義(apis),Swagger會掃描該包下所有Controller定義的API,並產生文檔內容(除了被@ApiIgnore指定的請求)
1.3 在controller上編寫我們的接口信息
@RestController
@RequestMapping("/alarmDevice")
@Api(tags = "設備")
public class AlarmDeviceController {
@Autowired
private IAlarmDeviceService alarmDeviceService;
/** * 根據name查詢設備信息 */
@GetMapping("/name/get")
@ApiOperation(value = "根據name查詢設備信息", notes = "查詢數據庫中某個設備的信息")
public BaseResponse<List<AlarmDevice>> getByName(@ApiParam(name = "name", value = "設備名稱", required = true) String name){
List<AlarmDevice> alarmDeviceList = alarmDeviceService.getByName(name);
return new BaseResponse<>("200",alarmDeviceList);
}
@GetMapping("/{id}")
@ApiOperation(value = "根據id查詢設備信息", notes = "查詢數據庫中某個設備的信息")
@ApiImplicitParam(name = "name", value = "設備唯一標識", required = true, dataType = "string",paramType = "path")
public BaseResponse<List<AlarmDevice>> get(@PathVariable String id){
List<AlarmDevice> alarmDeviceList = alarmDeviceService.getById(id);
return new BaseResponse<>("200",alarmDeviceList);
}
//@ApiIgnore//使用該注解忽略這個API
/** * 如果方法參數過多,可使用ApiImplicitParams和ApiImplicitParam寫在方法上 */
@GetMapping("/list")
@ApiOperation(value = "分頁查詢設備列表", notes = "")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNo", value = "頁碼", required = true, dataType = "Long"),
@ApiImplicitParam(name = "pageNum", value = "頁數", required = true, dataType = "Long")
})
public BaseResponse<List<AlarmDevice>> list(Integer pageNo, Integer pageNum){
//List<AlarmDevice> alarmDeviceList = alarmDeviceService.getByName(name);
return new BaseResponse<List<AlarmDevice>>("200",null);
}
}
@ApiModel(value="user對象",description="用戶對象user")
public class User{
@ApiModelProperty(value="用戶名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="狀態",name="state",required=true)
private Integer state;
private String password;
private String nickName;
@ApiModelProperty(value="id數組",hidden=true)
private String[] ids;
- @Api:修飾整個類,描述Controller的作用
- @ApiOperation:描述一個類的一個方法,或者說一個接口
- @ApiParam:單個參數描述
- @ApiModel:用對象來接收參數
- @ApiIgnore:使用該注解忽略這個API
- @ApiParamImplicitL:一個請求參數
- @ApiParamsImplicit 多個請求參數
更詳細的swagger的注解含義可以參考github官網和這篇博客
1.4 訪問http://ip:port/swagger-ui.html卻404?
很有可能是靜態資源映射的問題,可以嘗試添加:
@Configuration
public class ServletContextConfig extends WebMvcConfigurationSupport {
/** * 這個自定義的類繼承自WebMvcConfigurationSupport,spring boot有一個子類EnableWebMvcConfiguration,並且是自動config的. * 我們知道,如果一個類用戶自己在容器中生成了bean,spring boot就不會幫你自動config。 * 所以,問題的原因是我們把spring boot自定義的那個bean覆蓋了 */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
2 結合swagger2markup生成離線文檔PDF/HTML格式
最常用的就是swagger2markup,即利用swagger.json生成asciidoc文檔,然后轉為html,pdf格式的文檔。但是配置有些繁瑣,所以就想可不可以利用一個demo工程直接訪問現有項目的swagger接口來生成離線文檔,這樣就不會在當前項目引入額外的代碼與配置。
demo工程地址為https://github.com/spiritn/spring-swagger2markup-demo.git。只需要將Swagger2MarkupTest里的SWAGGER_URL修改為自己項目的swagger接口地址,如
private static final String SWAGGER_URL = "http://localhost:8085/v2/api-docs";
保證接口可以訪問,然后運行mvn clean test
,即可在target/asciidoc/html 或者target/asciidoc/pdf下生成離線文檔,效果很不錯,中文也支持的很好,可以點擊dto對象跳轉到對應的描述: