- Swagger实用性:
- 首先Controller的方法的挨个展示
- 可以测试对应路径的Cotroller层的方法
- 可以看到你的实体类及其属性相关信息
- 还能方便多人协同开发后端接口
2.接下来开始正题
(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配置类
package com.example.eduExample.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
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;
import java.util.ArrayList;
@Configuration//标明该类为配置类(也会放入容器中)
@EnableSwagger2//开启Swagger
public class SwaggerConfig {
@Bean
public Docket docket1(Environment environment) {
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket(Environment environment) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.eduExample.controller"))
.build().groupName("yth");
}
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("yth", "http:localhost:8080/", "123@a.com");
return new ApiInfo("Api Documentation Title"
, "Api Documentation Description"
, "1.0"
, "urn:tos"
, contact
, "Apache 2.0"
, "http://www.apache.org/licenses/LICENSE-2.0"
, new ArrayList());
}
}
(3)可以输入路径访问Swagger页面了(在路径后面加swagger-ui.html)
以上,SpringBoot整合Swagger操作基本结束
注意:
但是如果报错的话是大概率是因为你的SpringBoot的版本太高了,具体原因如下:
Springfox 假设 Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x版本的默认匹配策略是 path-pattern-matcher,这就造成了上面的报错。