OpenAPI 生成器为已实现的方法返回 501
Posted
技术标签:
【中文标题】OpenAPI 生成器为已实现的方法返回 501【英文标题】:OpenAPI generator returns 501 for implemented method 【发布时间】:2021-12-09 19:26:47 【问题描述】:我已经使用 openAPI 生成器 maven 插件生成了 rest api,并且我已经覆盖了 MyApiDelegate
接口的默认方法,但是 /endpoint
上的 POST 请求提供了 501 NOT IMPLEMENTED,就好像我没有给出我自己的实现一样MyApiDelegateImpl 中的那个方法。
Maven 插件配置:
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.3.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<configOptions>
<inputSpec>$project.basedir/src/main/resources/latest.yaml</inputSpec>
<generatorName>spring</generatorName>
<apiPackage>my.rest.api</apiPackage>
<modelPackage>my.rest.model</modelPackage>
<supportingFilesToGenerate>ApiUtil.java</supportingFilesToGenerate>
<delegatePattern>true</delegatePattern>
<useBeanValidation>false</useBeanValidation>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
/* code generated by plugin */
package my.rest;
public interface MyApiDelegate
default Optional<NativeWebRequest> getRequest()
return Optional.empty();
default ResponseEntity<Void> doSmth(Smth smth)
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
package my.rest.api;
public interface MyApi
default MyApiDelegate getDelegate()
return new MyApiDelegate() ;
/*...Api operations annotations...*/
@RequestMapping(value = "/endpoint",
produces = "application/json" ,
consumes = "application/json", "application/xml" ,
method = RequestMethod.POST)
default ResponseEntity<Void> doSmth(@ApiParam(value = "" ,required=true) @RequestBody Smth smth)
return getDelegate().doSmth(smth);
我的实现:
package my.rest.api;
@Service
@RequiredArgsConstructor
public class MyApiDelegateImpl implements MyApiDelegate
private final MyService s;
@Override
public ResponseEntity<Void> doSmth(Smth smth)
s.doIt(smth);
return ResponseEntity.ok().build();
如何让我的程序在具体类中使用我自己的方法实现,而不是接口中提供的默认实现?
【问题讨论】:
【参考方案1】:直接实现MyApi
接口和方法doSmth
在其中,是这样做的一种方式。您的具体类不需要所有与 Web 相关的注释,而只需像普通方法一样具有参数和返回值。
我不明白如何初始化接口MyApiDelegate
,但由于getDelegate
返回它的实现,所以调用doSmth
的默认实现并返回HttpStatus.NOT_IMPLEMENTED
。
另外一件需要注意的事情是确保部署知道使用实现类。如果您使用的是 spring web,那么仅仅标记您的具体类 @RestController 就足够了。
【讨论】:
由于openAPI生成器使用Delegate DP,所以MyApi接口中默认方法的目的只是调用相应的服务,因此并不能解决我的问题。由于 openAPI 生成器插件注解 Controller 就足够了。我真正不明白的是为什么我的类使用接口中的默认实现,即使我已经创建了一个具有覆盖它的方法的具体类。以上是关于OpenAPI 生成器为已实现的方法返回 501的主要内容,如果未能解决你的问题,请参考以下文章
如何从 OpenAPI 3.0 yaml 文件生成 JSON 示例?
REST easy with kbmMW #20 – OpenAPI and Swagger UI
Auth::guest() 为已登录和已注销的用户返回 true