Swagger2簡介
1.隨項目自動生成強大RESTful API文檔,減少工作量
2.API文檔與代碼整合在一起,便於同步更新API說明
3.頁面測試功能來調試每個RESTful API
springboot集成Swagger2步驟
1. 新建一個Springboot項目
2. 導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
3. 編寫控制器
@RestController
public class Mycontroller {
@GetMapping({"/","hello"})
public String hello(){
return "helloword";
}
}
4. 編寫swagger的配置類
寫上注解
@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
啟動項目運行
瀏覽器輸入 http://localhost:8080/swagger-ui.html
我們所寫的controller方法都會被檢測到
5. 配置Swagger2
- 配置Swagger信息 info
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apinfo());
}
public ApiInfo apinfo(){
Contact contact = new Contact(
"joker_dj",
"https://www.cnblogs.com/joker-dj/",
"2332810801@qq.com");
return new ApiInfo("joker_dj的api文檔",
"Api Documentation",
"1.0",
"https://www.cnblogs.com/joker-dj/",
contact, "Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
運行看效果
2. 配置多個分組
多配置幾個Docket即可
3. 配置其他的信息 不一一解釋 都有注釋
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apinfo())
//是否啟用swagger false不啟用
.enable(true)
.groupName("joker_dj")
.select()
/*
配置RequestHandlerSelectors 掃描接口的方式
指定掃描的包basePackage
any()掃描全部
none()不掃描
withClassAnnotation:掃描類上的注解
*/
.apis(RequestHandlerSelectors.basePackage("com.dj.controller"))
//過濾路徑 比如PathSelectors.ant("login/**")
// .paths(PathSelectors.ant(""))
.build();
}
6.添加注釋信息
- 編寫user實體
- 在controller返回一個user
運行
會檢測到我們所有寫的controller方法
也可以進行測試方法
點擊Try it out
- 點擊運行
這里就會返回我們測試接口的信息以及響應的結果
- 給類,屬性和方法添加注釋信息
在user實體類添加注解
@ApiModel:給類添加注釋
@ApiModelProperty :給字段添加注釋
@ApiModel("用戶實體類")
public class user {
@ApiModelProperty("用戶名")
public String username;
@ApiModelProperty("密碼")
public String password;
}
運行看效果
添加到controller上
@ApiOperation
運行看效果
5. 發送數據 測試接口
在controller中編寫代碼
運行測試
輸入用戶名 密碼 點擊測試
這樣就返回了我們數據
總結:Swagger這個工具主要是針對開發人員測試接口來使用的,
注意:在項目上線的時候己得吧Swagger給關閉 防止接口暴露 (安全)