swagger2的作用
在项目中,经常需要通过接口来与前端对接,对字段之类的,swagger2的出现能够有效的提示对接效率,降低沟通成本。swagger2可以在实体,类,方法,参数上添加中文注解,以标注对应的接口、字段、参数等对应的含义,前端只需要通过可视化的UI就能得到接口需要的地址、字段等信息。
1、引入jar包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.9.2</version>
</dependency>
2、创建swagger配置类
package com.cnnc.vue.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;
/**
* 接口API
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.cnnc.vue.controller")) //Controller接口输出类所在包
.paths(PathSelectors.any())
.build();
}
/**
* 页面显示信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot使⽤Swagger2构建RESTul APIs") //显示提示语
.description("swagger2的api")
.termsOfServiceUrl("url")
.contact(new Contact("","url","mail"))
.version("1.0")
.build();
}
}
配置完成后可直接启动项目。
3、启动报错
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
解决方案:
原因: 这是因为Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。
解决:在application.properties里配置:spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER。
报404
原因:是swagger-ui版本太高了,降低springfox-swagger-ui版本:2.9.2
4、访问地址:
http://localhost:8080/swagger-ui.html