<!-- swagger -->
<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.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
package com.sock.wrap.config;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
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;
import java.util.Collection;
import java.util.List;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
/**
* 配置基本信息
* @return
*/
@Bean
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API测试文档")
.description("接口测试文档")
.termsOfServiceUrl("github")
.contact(new Contact("联系人名字","网址","邮箱"))
.version("v1.0")
.build();
}
/**
* 配置文档生成最佳实践
* @param apiInfo
* @return
*/
@Bean
public Docket createRestApi(ApiInfo apiInfo) {
return new Docket(DocumentationType.OAS_30) // 指定Swagger3.0版本
.enable(true)// 开关
.apiInfo(apiInfo)
// 组名
.groupName("SwaggerGroupOneAPI")
.select()
// 扫描地址
.apis(RequestHandlerSelectors.basePackage("com.sock.wrap.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 增加如下配置可解决Spring Boot 6.x 与Swagger 3.0.0 不兼容问题
**/
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
}
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
}
@RestController
@Api(tags="用户数据接口")
public class SwaggerController {
@ApiOperation(value = "查询用户", notes="根据id查询用户")
@ApiImplicitParam(paramType = "path", name = "id", value = "用户id", required = true)
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Integer id){
return "/user/" + id;
}
@ApiResponses({
@ApiResponse(code = 200, message = "删除成功!"),
@ApiResponse(code = 500, message = "删除失败!")
})
@ApiOperation(value = "删除用户", notes = "通过id删除用户")
@DeleteMapping("/user/{id}")
public Integer deleteUserById(@PathVariable Integer id){
return id;
}
@ApiOperation(value = "添加用户", notes = "添加一个用户,传入用户名和地址")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "id", value = "id", required = true, defaultValue = "1"),
@ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, defaultValue = "张三"),
@ApiImplicitParam(paramType = "query", name = "address", value = "地址", required = true, defaultValue = "北京"),
@ApiImplicitParam(paramType = "query", name = "gender", value = "性别", required = true, defaultValue = "男")
})
@PostMapping("/user")
public String addUser(@RequestParam Integer id, @RequestParam String username, @RequestParam String address, @RequestParam String gender){
return username + ":" + address;
}
@ApiOperation(value = "修改用户", notes = "修改用户,传入用户信息")
@PutMapping("/user")
public String updateUser(@RequestBody User user){
return user.toString();
}
@GetMapping("/ignore")
@ApiIgnore
public void ignoreMethod(){}
}
@ApiModel(value = "用户实体类", description = "用户描述信息")
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户地址")
private String address;
@ApiModelProperty(value = "用户性别")
private String gender;
......
}
http://localhost:8080/swagger-ui/index.html
1、版本问题
Swagger 版本2.9.2对应Spring Boot 版本2.6.x以下,否则会报如下错误
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
SpringBoot 2.6版本以上,直接使用Swagger 版本3.0.0,注意添加兼容性配置
2、访问路径问题
swagger 3.0 的默认路径是
http://localhost:8080/swagger-ui/index.html
其中 index.html 可以省略不写:
http://localhost:8080/swagger-ui/
而 Swagger 2.9 的默认路径是
http://localhost:8080/swagger-ui.html
https://blog.csdn.net/shaotaiban1097/article/details/113629680
https://www.cnblogs.com/antLaddie/p/17418078.html#_label1