一、添加依賴
在pom.xml檔案中添加swagger相關依賴
<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>
二、建立配置類
swagger的configuration
@Configuration
@EnableSwagger2 //開啟Swagger2
public class SwaggerConfiguration {
//配置swagger的Docket的bean的執行個體
@Bean
public Docket createRestApi() {
//public Docket createRestApi(Environment environment)
//設定要顯示的Swagger環境Profiles profiles = Profiles.of("dev", "pro");
//Profiles profiles = Profiles.of("dev");
//通過environment.acceptsProfiles判斷是否處在自己設定的環境當中
//boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//enable是否啟動Swagger,如果為false,則Swagger不能在浏覽器中通路
//.enable(flag)
.select()
//RequestHandlerSelectors配置要掃描接口的方式
//basePackage指定要掃描的包
//any() 掃描全部
.apis(RequestHandlerSelectors.basePackage("com.until.oracle.controller"))
//過濾什麼路徑
.paths(PathSelectors.any())
.build();
}
//配置Swagger2資訊
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger建構api文檔")//網站标題
.description("簡單優雅的restfun風格,http://blog.csdn.net/saytime")//網站描述
.version("v1.0")//版本号
.contact(new Contact("吳", "http://blog.csdn.net/saytime", "[email protected]"))//聯系人資訊
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.license("Apache 2.0")//協定
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
.build();
}
}
三、注解
@ApiIgnore 可以用在類、方法上,方法參數中,用來屏蔽某些接口或參數,使其不在swagger-UI頁面上顯示。
@Api
用在類上,說明該類的作用。可以标記一個Controller類做為swagger 文檔資源,使用方式
@Api(value = "使用者", tags = {"使用者資訊子產品"})
@ApiOperation用在方法上,說明方法的作用,每一個url資源的定義,使用方式
@ApiOperation(value="查詢所有使用者資訊", notes="擷取所有使用者資訊")
@ApiImplicitParams用于方法,包含多個 @ApiImplicitParam
1、name :參數名
2、value : 描述參數名
3、required : 該參數是否必填
4、dataType :參數的資料類型
5、example:舉例
6、paramType :查詢參數類型。這裡有幾種形式:
類型 | 作用 |
path | 以位址的形式送出資料 |
query | 直接跟參數完成自動映射指派 |
body | 以流的形式送出 僅支援POST |
header | 參數在request headers 裡邊送出 |
form | 以form表單的形式送出 僅支援POST |
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "username", value = "使用者名", required = true, dataType = "String", paramType = "query")
})