1 maven 导入依赖
<!-- swagger2 api -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2 新增配置类
package com.es.config;
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.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.es.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("es api")
.description("elasticsearch restful api")
.version("1.0")
.build();
}
}
3 访问:
htthttp://localhost:8889/swagger-ui.html
4 坑 & 解决方案:
No mapping found for HTTP request with URI [/swagger-resources/configuration/ui] in DispatcherServlet with name ‘dispatcherServlet’
这个错误,是因为资源映射问题导致。
我们在访问http://127.0.0.1:8188/swagger-ui.html 时,这个swagger-ui.html相关的所有前端静态文件都在springfox-swagger-ui-2.6.1.jar里面。目录如下:
Spring Boot自动配置本身不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。我们加上这个映射即可。代码如下:
@Configuration
class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/")
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
}
}
同时,在启动类上添加注解@EnableWebMvc。完整的Spring Boot集成Swagger2构建自动化Rest API文档工程示例,源码参考: