[英]Swagger 2.0 Implementation in spring MVC rest api with spring boot
如何为现有的 Spring 休息服务添加 swagger? 使用 spingfox 或 swagger UI
这是使用 Spring Boot 应用程序
首先使用 spring 创建一个普通的 REST API,
1.
在你的 pom.xml 中,确保你有所有的 swagger 依赖项。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
不要忘记@EnableSwagger2
请记住使用 docket 方法添加 bean,否则它会添加垃圾 api 值
3)在你的休息控制器中
不要错过在 swagger 编辑器中进行正确处理所需的 api 注释
稍后将出现在 swagger UI 中。
在完成所有这些之后,如果你运行你的 spring boot 应用程序并且
就是这样,您应该获得 api 文档
喜欢
对于 Swagger UI
如果您在 swagger UI 中遇到错误
无法从服务器读取。 它可能没有适当的访问控制来源设置。
要解决此问题,您需要对 swagger 进行 access-control-origin 设置,
首先为 chrome/任何浏览器添加一个 CORS 插件 - 在这个下面添加你的 url
然后这将启动您的 swagger UI,并且您必须能够在浏览器上看到输出。
如果您使用的是 jackson,请确保使用正确的版本号
java.lang.NoSuchMethodError: com.fasterxml.jackson。
或者任何其他与 Jackson 相关的错误都是由于 pom.xml 中的 Jackson 核心和 Jackson 数据绑定依赖项之间的版本不匹配而引起的。
确保你有正确的 pom。
就我而言,
问题是我得到了不兼容的 jackson-core 和 jackson-databind 版本 - jackson-core 2.0.5 正在被引入,但我相信至少需要 2.1.0。
异常的第一行告诉你它找不到 JsonParser.getValueAsString() 方法,查看 2.0.5 的 API 文档,该方法确实不存在。 看起来它是在 2.1.0 中添加的。
因此,您需要修复依赖项 - 最有可能通过排除 2.0.5 并包括 2.1.0。
其次,
如果你必须使用这个 Swagger 生成的 codegen 或 swagger codegen
首先需要在pom.xml中为Swagger添加maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
然后添加 SwaggerConfiguration 类:
package com.mycompany.rest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created by smv on 10.09.2016.
*/
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
这就是您的 springboot 项目的最小 Swagger UI 配置所需的全部内容。 如果您有任何问题,可以参考带有模拟项目https://github.com/mv200580/springboot-rest 的示例存储库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.