Springboot整合swagger的简单使用
1.添加swagger依赖
<!--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>
2.编写SwaggerConfig配置类
@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket createRestApi(Environment environment) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)
.select()
.apis(RequestHandlerSelectors.basePackage("com.study.sims"))//此路径为Swagger扫描的包路径,一般为dao的上一层
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact("user", "url", "e-mail");
return new ApiInfoBuilder()
.title("Swagger api文档")
.description("Swagger描述")
.version("1.0")
.build();
}
3.在启动类上添加swagger启动注解
@EnableSwagger2注解用来启动swagger
4.访问swagger地址:http://localhost:1001/swagger-ui.html(端口是你服务器的端口,这里我用的自己的)
问题:如果在访问Swagger地址的时候出现错误页面,可能是你的swagger静态资源被过滤掉了,解决办法如下:
SwaggerConfig配置类继承WebMvcConfigurerAdapter类,重写addResourceHandlers方法(以下配置路径不用改,swagger默认的静态资源路径)
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}