3

有没有办法从 Swagger/OpenAPI 规范生成控制器 Spring MVC 代码?

我知道 Swagger 可以从现有的 Spring 代码中生成,但这可能反过来吗?

4

2 回答 2

7

您基本上是在寻找招摇的服务器端代码的生成。如果您想在构建应用程序时生成它,并且如果您使用的是 maven,则可以使用以下插件:

<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>${swagger.codegen.version}</version>
<executions>
  <execution>
    <goals>
      <goal>generate</goal>
    </goals>
    <configuration>
      <inputSpec>${swagger.yaml.file}</inputSpec>
      <language>spring</language>
      <configOptions>
        <sourceFolder>${swagger.generated.sourcepath}</sourceFolder>
        <!-- <interfaceOnly>true</interfaceOnly> -->
        <dateLibrary>java8</dateLibrary>
      </configOptions>
      <typeMappings>
        <typeMapping>OffsetDateTime=Instant</typeMapping>
      </typeMappings>
      <importMappings>
        <importMapping>java.time.OffsetDateTime=java.time.Instant</importMapping>
      </importMappings>
      <modelPackage>${project.groupId}.${project.artifactId}.swagger.model</modelPackage>
      <apiPackage>${project.groupId}.${project.artifactId}.swagger.api</apiPackage>
      <invokerPackage>${project.groupId}.${project.artifactId}.swagger.invoker</invokerPackage>
    </configuration>
  </execution>
</executions>
</plugin>

请注意注释部分interfaceOnly,如果设置为 true,它只会创建默认为 as 的 API 类,NOT_IMPLEMENTED您必须编写实现。

添加以下依赖项:

<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-annotations</artifactId>
  <version>${swagger.annotations.version}</version>
  <scope>compile</scope>
</dependency>

我使用了以下属性:

<properties>
    <swagger.codegen.version>2.4.1</swagger.codegen.version>
    <swagger.yaml.file>${project.basedir}/swagger.yaml</swagger.yaml.file>
    <swagger.annotations.version>1.5.21</swagger.annotations.version>
    <swagger.generated.sourcepath>src/main/java</swagger.generated.sourcepath>
</properties>

当 swagger 文件发生更改时,需要手动生成控制器的另一种静态方法是使用swagger editor

在此处输入图像描述

于 2019-05-28T14:36:09.573 回答
3

是的,可以从命令行使用swagger codegen或使用swagger editor

于 2016-10-18T11:58:43.533 回答