更改 Spring openapi-generator-maven-plugin 生成的接口的返回类型

Chr*_*one 8 java spring spring-boot openapi openapi-generator

我已成功从 .yaml open-api 描述符文件生成接口,但是,如问题标题所示,我希望将这些接口的响应类型从 ResponseEntity 更改为我自己的类型。基本上而不是具有此签名的接口:

 ResponseEntity<Void> clearCache();
Run Code Online (Sandbox Code Playgroud)

对于基本上以这种方式实现的方法:

public void clearCache(){ //do something}
Run Code Online (Sandbox Code Playgroud)

我希望生成的界面就像

void clearCache();
Run Code Online (Sandbox Code Playgroud)

对于我自己定义的类来说也是如此,而不是ResponseEntity<MyBook> getBook(String ISBN);我希望它只用作MyBook返回类型,所以它应该看起来像MyBook getBook(String ISBN); 我用于 openapi-generator 插件的当前设置是

        <plugin>
            <groupId>org.openapitools</groupId>
            <artifactId>openapi-generator-maven-plugin</artifactId>
            <version>4.3.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>my-own-service-be/src/main/resources/api-docs.yaml</inputSpec>
                        <generatorName>spring</generatorName>
                        <additionalProperties>
                             <additionalProperty>skipDefaultInterface=true</additionalProperty>
                            <additionalProperty>interfaceOnly=true</additionalProperty>
                        </additionalProperties>
                        <generateApis>true</generateApis>
                        <apiPackage>controller</apiPackage>
                        <supportingFilesToGenerate>false</supportingFilesToGenerate>
                        <modelPackage>dto</modelPackage>
                        <generateModelTests>false</generateModelTests>
                        <generateApiTests>false</generateApiTests>
                    </configuration>
                </execution>
            </executions>
        </plugin>
Run Code Online (Sandbox Code Playgroud)

phi*_*ous 6

我们最近遇到了类似的挑战。您需要做的就是调整模板。为此,您需要从 OpenAPI 项目中找到生成器的源模板。在您的情况下,这就是这个api.mustache文件

只需将其复制到您的src/main/resources/文件夹(可能在名为 的子文件夹中custom)并根据您的需要进行调整,即替换响应类型。

然后,您需要调整您的pom.xml自定义模板文件,以便实际使用您的自定义模板文件:

     <configuration>

        <!-- The following line is crucial: -->
        <templateDirectory>${project.basedir}/src/main/resources/custom</templateDirectory>

        <inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec>
        <generatorName>spring</generatorName>
        <configOptions>
            <sourceFolder>src/gen/java/main</sourceFolder>
        </configOptions>
    </configuration>
Run Code Online (Sandbox Code Playgroud)

另请参阅此模板文档以获取有关该主题的更多信息。