简体   繁体   中英

Generate Spring MVC controller from Swagger/OpenAPI

Is there a way how to generate controller Spring MVC code from Swagger/OpenAPI specification?

I know Swagger can be generated from existing Spring code but is this possible the other way round ?

是的,可以使用命令行中的swagger codegen或使用swagger编辑器

You are basically looking for generation of swagger server-side code. If you would like to generate it while you are building your application and if you are using maven you can use the following plugin:

<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>

Please note the commented part interfaceOnly if set to true, it will only create the APIs class with default as NOT_IMPLEMENTED and you would have to write the implementation.

Add following dependency:

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

I used the following properties:

<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>

The other static approach that would require the generation of controller manually when there is a change in the swagger file would be to use swagger editor .

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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