SpringBoot2.x整合Swagger2构建接口文档及问题

it2025-09-04  4

SpringBoot2.x整合Swagger2

1、项目环境

SpringBoot:2.3.4 Swagger2:2.2.2 jdk:1.8

2、添加Swagger2依赖

在pom.xml中添加Swagger2依赖:

<!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency>

3、创建Swagger2的配置类

package com.zbh.studys.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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @ClassName SwaggerConfig * @Description TODO * @Author * @Date 2020/10/15 9:07 **/ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ // DocumentationType.SWAGGER_2:告诉Docketbean使用的Swagger规范版本2 return new Docket(DocumentationType.SWAGGER_2) // 指定构建api文档的详细信息的方法 .apiInfo(apiInfo()) // 用于定义那些控制器及其生成的文档中应包含那些方法 .select() // 指定要生成api接口的包路径,这里把controller作为包路径,生成controller中的所有接口 .apis(RequestHandlerSelectors.basePackage("com.zbh.studys.controller")) // 允许根据路径映射定义应包含那个控制器的方法,PathSelectors.any()代表匹配所有的URL,但你可以使用正则表达式来限制。 .paths(PathSelectors.any()) .build(); } /** * 构建api文档的详细信息 * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() // 设置页面标题 .title("Spring Boot搭建实际项目中开发的架构") // 设置接口描述 .description("练习Spring Boot课程") // 设置联系方式 .contact("作者") // 设置版本 .version("1.0") // 构建 .build(); } }

4、将Swagger Core注释添加到模型类中

package com.zbh.studys.Entiy; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @ClassName User * @Description TODO * @Author zhangbh * @Date 2020/10/15 9:23 **/ // 定义在类级别上 @ApiModel(description = "用户实体类") public class User { /** * 定义在字段级别上,该注解对于提供示例值非常有用,这不仅适用于用户的指导, * 而且还可以在使用Swagger UI作为REST客户端来测试服务时预填充请求有效负载。 * position指定属性在文档中显示的顺序, * 首先提供重要或必需的属性或属于一起的组属性是有用的, * 否则属性将按照字母顺序列出。 * / @ApiModelProperty(value = "用户ID", position = 0) private Long id; @ApiModelProperty(value = "用户名称", position = 1) private String username; @ApiModelProperty(value = "用户密码", position = 2) private String password;

5、将Swagger Core注释添加到控制类中

package com.zbh.studys.controller; import com.zbh.studys.Entiy.User; import com.zbh.studys.result.JsonResult; import com.zbh.studys.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @ClassName UserController * @Description TODO * @Author zhangbh * @Date 2020/10/15 9:18 **/ @RestController @Api(value = "用户信息接口") // 描述整个控制器 public class UserController { @Resource private UserService userService; @GetMapping("/getUser/{id}") @ApiOperation(value = "根据用户唯一标识获取用户信息") // 用于方法级别的描述 // @ApiParam 用于方法参数的描述 public JsonResult<User> getUserInfo(@PathVariable @ApiParam(value = "用户唯一标识") Long id){ User user = new User(id, "XXX", "123456"); return new JsonResult<>(user); } }

配置到此结束,此时是可以启动应用并使用Swagger的,但可也有可能会遇到一些问题。

SpringBoot2.x整合Swagger2可能出现的问题

问题一:

启动失败,报这个错误Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed,详细错误如下:

*************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration required a single bean, but 15 were found: - modelBuilderPluginRegistry: defined in null - modelPropertyBuilderPluginRegistry: defined in null - typeNameProviderPluginRegistry: defined in null - documentationPluginRegistry: defined in null - apiListingBuilderPluginRegistry: defined in null - operationBuilderPluginRegistry: defined in null - parameterBuilderPluginRegistry: defined in null - expandedParameterBuilderPluginRegistry: defined in null - resourceGroupingStrategyRegistry: defined in null - operationModelsProviderPluginRegistry: defined in null - defaultsProviderPluginRegistry: defined in null - pathDecoratorRegistry: defined in null - relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class] - linkDiscovererRegistry: defined in null - entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class] Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed Process finished with exit code 1

报这个错误是因为,SpringBoot版本太高或者swagger版本太低了导致的,就比如我使用的是SpringBoot2.3.4,Swagger2.2.2,这个就不行。可以将SpringBoot改成2.0.3或者将Swagger改成2.9.2就可以了。

<!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency>

问题二:

我们在启动后,在浏览器输入http://localhost:8080/swagger-ui.html时可能会报404错误,这个问题是因为我们的项目是纯restful前后端分离的项目,可能会无法访问静态资源,可以修改一下SwaggerConfig配置类,来做一下映射关系。

@Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 解决swagger无法访问 registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); // 解决swagger的js文件无法访问 registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); }

问题三:

还有一个问题,暂时复现不了,就先不详细写了,等遇到了再详细写。大致先说一下这个问题,就是类型转换错误,‘java.lang.NumberFormatException: For input string: " "’。原因是因为:io.springfox:springfox-swagger2:2.9.2这个包下的swagger-modelsde的版本是1.5.10,可以排除这个依赖,添加高版本的依赖即可。

<!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.21</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.21</version> </dependency>
最新回复(0)