Gan*_*esh 11 spring swagger springfox
我已经使用 springfox 2.0 配置了我的 spring 项目。我能够用它生成开放的 api 规范。
"paths": {
"/test/testinfo": {
"post": {
"tags": [
"test-controller"
],
"summary": "getTestInfo",
"operationId": "getTestInfoInfoUsingGET",
"consumes": [
"application/json"
],
"produces": [
"application/json"
]
Run Code Online (Sandbox Code Playgroud)
正如你所看到的 operationId 的值是格式
[java_method_name_here]Using[HTTP_verb_here]
Run Code Online (Sandbox Code Playgroud)
前任。getPetsUsingGET
此 operationId 在使用 swagger-codegen 生成客户端时使用。有谁知道如何自定义它?我知道这可以通过每个 api 使用来完成,@ApiOperation
但是有没有更通用的方法来为所有 api 定义这种格式?
我们也可以使用这种覆盖默认操作 ID 的昵称方法。
@ApiOperation(value = "", nickname = "getMeAllThePetsPlease")
@RequestMapping(value = "/pets", method = RequestMethod.GET)
public Model getAllThePets() {
...
}
Run Code Online (Sandbox Code Playgroud)
所以我们将覆盖operationId: getAllThePetsByGet和getMeAllThePetsPlease。
注意:昵称将覆盖 operationId,因此可以相应地进行自定义。
您可以创建自己的插件来做到这一点。这是我们如何在 springfox 中使用相同插件技术进行操作的示例。
@Component
@Order(YOUR_PLUGIN_ORDER) // > Ordered.HIGHEST_PRECEDENCE + 1000
public class OperationNicknameIntoUniqueIdReader implements OperationBuilderPlugin {
@Override
public void apply(OperationContext context) {
//Create your own transformation to format the name in the way
//that you prefer
String operationNameStem = transformName(context.getName());
//Update the method name stem that is used to generate a unique id
context.operationBuilder().codegenMethodNameStem(operationNameStem);
}
...
}
Run Code Online (Sandbox Code Playgroud)
注意:无论你想出什么词干,springfox 都会确保它在所有 API 中都是独一无二的。因此,如果您有一个重复的命名方法,它将在您唯一名称的末尾开始编号方案。例如,如果getCustomer
不是唯一的,它将生成一个唯一的 idgetCustomer_1
等。
基于@bdzzaid 的更短更清晰的代码版本:
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000)
public class SwaggerIncludeMissingNicknameIntoUniqueIdReader implements OperationBuilderPlugin {
@Override
public void apply(OperationContext context) {
Optional<ApiOperation> methodAnnotation = context.findControllerAnnotation(ApiOperation.class);
Operation operationBuilder = context.operationBuilder().build();
String uniqueId = operationBuilder.getUniqueId().replaceAll("Using(GET|POST|PUT|DELETE)", "");
// If nickname exists, populate the value of nickname annotation into uniqueId
String fillId = methodAnnotation.transform(ApiOperation::nickname).or(uniqueId);
context.operationBuilder().uniqueId(fillId);
context.operationBuilder().codegenMethodNameStem(fillId);
}
@Override
public boolean supports(DocumentationType delimiter) {
return SwaggerPluginSupport.pluginDoesApply(delimiter);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5844 次 |
最近记录: |