简体   繁体   English

我可以从现有的Java代码中获取Swagger文档吗?

[英]Can I obtain the Swagger documentation from pre existing Java code?

I am absolutly new in Swagger and I have the following doubt: 我绝对是Swagger的新手,我有以下疑问:

I know that gnerally I have to create Swagger document before code my REST API and the use this document to create my API (I know that from the Swagger Editor I can also generate my API server automatically). 我知道一般来说,我必须先编写Swagger文档,然后再编写REST API并使用该文档来创建我的API(我知道从Swagger编辑器中,我也可以自动生成我的API服务器)。

My problem is the following one: 我的问题是以下一个:

I am working on a Java application (a Spring Boot application) that implements my REST API. 我正在开发实现REST API的Java应用程序(Spring Boot应用程序)。 I want to use Swagger to create my API documentation. 我想使用Swagger创建我的API文档。

Exist a way to automatically do it? 存在自动执行的方法吗? From my Java code to the Swagger yaml file? 从我的Java代码到Swagger yaml文件? For example annoting my Java code in some way that could be parsed by some tool? 例如,以某种工具可以解析的方式注释我的Java代码?

Yes, there is a tool which can easily generate the swagger documentation from the code you have already written. 是的,有一个工具可以轻松地从您已经编写的代码中生成详尽的文档。

This included into a Spring Appllication will create the documentation https://springfox.github.io/springfox/docs/current/ Spring Appllication包含的内容将创建文档https://springfox.github.io/springfox/docs/current/

To my mind this is the right way to it. 我认为这是正确的方法。 Don't create a documentation and have the code generated, rather generate the documentation. 不要创建文档并生成代码,而要生成文档。 That's the way Javadoc is created as well. 这也是创建Javadoc的方式。

You don't need to annotate nothing in particular. 您无需特别注释。

Create a class similar to the following to access the API with Swagger : 创建类似于以下内容的类以使用Swagger访问API:

@Configuration
@EnableSwagger2
public class SwaggerConfig{

  @Bean
  public Docket api(){

    return new Docket(DocumentationType.SWAGGER_2).select().apis(
        RequestHandlerSelectors.basePackage("com.yourcompany.restcode")).paths(PathSelectors.any()).build();
  }
}

Then access the API documentation with something like: 然后使用以下方式访问API文档:

localhost:8080/swagger-ui.html#/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM