使用openapi maven插件:
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.2.2</version>
</dependency>并使用pom配置生成spring引导控制器,如下所示:
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.2.2</version>
<executions>
<execution>
<id>spring-server</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<!-- specify the swagger yaml -->
<inputSpec>${project.resources[0].directory}/pet-store.yaml</inputSpec>
<!-- target to generate java client code -->
<generatorName>spring</generatorName>
<!-- pass any necessary config options -->
<configOptions>
<serializableModel>true</serializableModel>
<snapshotVersion>true</snapshotVersion>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>将生成这样的控制器:
@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}")
public class StoreApiController implements StoreApi {
private final NativeWebRequest request;
@org.springframework.beans.factory.annotation.Autowired
public StoreApiController(NativeWebRequest request) {
this.request = request;
}
@Override
public Optional<NativeWebRequest> getRequest() {
return Optional.ofNullable(request);
}
}这很好,但是我如何绑定到它来添加业务逻辑而不更改实际生成的代码呢?如果扩展控制器以添加业务逻辑,则会遇到各种问题。
您应该如何使用生成的代码,以扩展它以添加正确的业务逻辑,而不更改生成的代码,这将是不好的。
发布于 2020-01-29 16:20:07
我遇到你的问题时,我试图应付美洲国家组织3.0,因此使用上述的openapi-generator-maven-plugin。同时,我得到它来生成您所描述的内容。
我建议你通过
@ComponentScan注释,使其不包括生成的类(单独使用basePackages属性,也不与显式excludeFilters属性组合)。< code >H 210G 211是的,修改生成的类是不好的。我只是把它们作为创建实际控制器的起点。
修正:在以各种方式配置代码生成之后,找到了最好的解决方案,只创建API (接口)。这样,我就可以实现我的控制器,而不需要另一个实现来干扰它。
为此,我的插件配置现在看起来如下(使用configOptions/interfaceOnly选项):
<plugin>
<!-- generate REST API from spec -->
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.2.2</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec>
<generatorName>spring</generatorName>
<generateModels>true</generateModels>
<generateApis>true</generateApis>
<generateApiDocumentation>true</generateApiDocumentation>
<generateSupportingFiles>true</generateSupportingFiles>
<modelPackage>example.openapi.model</modelPackage>
<apiPackage>example.openapi.api</apiPackage>
<package>example.openapi</package>
<output>${generated.sources.restapi.dir}</output>
<configOptions>
<interfaceOnly>true</interfaceOnly>
<dateLibrary>java8-localdatetime</dateLibrary>
<java8>true</java8>
<useBeanValidation>true</useBeanValidation>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>https://stackoverflow.com/questions/59918961
复制相似问题