spring boot 2整合swagger-ui
阿新 • • 發佈:2019-03-07
eating sel info conf pom.xml paths defined des .config
1.添加mvn依賴
修改pom.xml
加入
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.5.0</version> </dependency>
2.創建配置類
在Application.java
同級創建Swagger2的配置類Swagger2
package com.tydt.decision; 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.Contact; import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2{ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.tydt.decision.controller")) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Decision Manage Swagger RESTful APIs") .description("Decision API") .termsOfServiceUrl("http://swagger.io/") .contact(new Contact("Beibei", "127.0.0.1", "[email protected]")) .version("1.0") .build(); } }
註:
- 如果出現下面情況
引入需要的包
但是啟動時又出現Error creating bean with name ‘apiDocumentationScanner‘ defined in URL
這是由於swagger依賴google的guava,需要添加依賴,而當前項目的guava版本與之不匹配,修改為
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version> </dependency>
- http://localhost:8090/swagger-ui.html頁面沒顯示
這是因為Spring Boot自動配置本身不會自動把/swagger-ui.html這個路徑映射到對應的目錄META-INF/resources/下面。加上這個映射即可
@Configuration public class WebMvcConfig implements WebMvcConfigurer { …… public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
解決了上面出現的問題,訪問http://localhost:8090/swagger-ui.html就能看到下面的頁面了
說明:
(1)通過@Configuration
註解,讓Spring來加載該類配置
(2)再通過@EnableSwagger2
註解來啟用Swagger2
(3)通過createRestApi
函數創建Docket
的Bean之後,apiInfo()
用來創建該Api的基本信息
(4)select()
函數返回一個ApiSelectorBuilder
實例用來控制哪些接口暴露給Swagger來展現
(5)指定掃描的包路徑來定義,會掃描該包下所有Controller定義的API,並產生文檔內容,除了用@ApiIgnore指定的
(6)通過@ApiOperation
註解來給API增加說明
(7)通過@ApiImplicitParams
(8)@ApiImplicitParam註解來給參數增加說明
spring boot 2整合swagger-ui