基於springboot2 框架整合(4):swagger ui 整合
阿新 • • 發佈:2018-12-07
前言
專案中使用了很多現成的框架,都是專案經理、架構師帶來的,從來沒有自己整合過!這次決定自己從零開始整合一次,以學習鞏固。過程中參考很多開源框架的思路,工具類等,若有侵權,請速速聯絡,一定妥善處理
一:簡介
前面已經把springboot+mybatis plus整合完了,也就是大名鼎鼎的ssm框架。現在新專案大多采用前後分離的開發模式,介面文件重要性不言而喻。swagger ui 是一個挺好用的介面文件生成工具。官網:https://swagger.io/
二:依賴
<!--swagger--> <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>
三:配置
SwaggerConfig.java
package org.itachi.frame.core.config.web;
import io.swagger.annotations.ApiOperation;
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.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
/**
* Swagger配置
*
* @author itachi
* @date 2018-10-05 18:09
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.example.demo";
public static final String VERSION = "1.0.0";
@Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//包下的類,才生成介面文件
//.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
//加了ApiOperation註解的類,才生成介面文件
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
//.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
//.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
.securitySchemes(security());
}
private List<ApiKey> security() {
return newArrayList(
new ApiKey("token", "token", "header")
);
}
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger API")
.description("This is to show api description")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version(VERSION)
.contact(new Contact("xxx", "", " [email protected]"))
.build();
}
}
四:使用
在控制器,實體新增相應的註解,便可生成api文件
目錄結構
五:測試
訪問 http://localhost:8080/swagger-ui.html#/
更多註解,請參考 《swagger常用註解說明》