spring boot 配置 swagger2 流程
- 在pom.xml 文件配置依赖 这个pom.xml 就是配置依赖的地方
<!-- 引入 swagger2 依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- swagger2 图形化依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
- 然后在Java项目里面创建一个config文件夹用来写对应的配置文件
package com.example.demo.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot 集成 Swagger2 测试接口文档")
.contact(new Contact("李白", "http://www.beidu.com", "libai@350.com"))
.version("1.0")
.description("API 描述")
.build();
}
}
- 这里有两个个需要注意的地方
- spring boot 不会自动更新引入的依赖 可能是我没配置吧 这里手动更新一下就好了。
- 主要是这个:引入的swagger2依赖和spring boot版本不一致 然后运行的时候报错如下:
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
造成这个主要原因是 当前的swagger2 版本 和 spring boot版本不匹配 修改下swagger版本就好了