spring rest docs自定义代码片段
Spring rest docs 文档插件在生成文档时会默认生成6个代码片段,自适应生成其它片段。通过阅读官方文档发现其可以自定义生成的代码片段,但是官方只说了可以自定义模版,修改现有的代码片段的方法。如果需要完全新增一个代码片段并没有说明。
在程序中通过debug发现生成文档的方法 document 其可以接受一个Snippet数组,除了默认的6个代码片段,其它代码片段如request-parameters,response-fields片段都会体现在这个Snippet数组上。
public static RestDocumentationResultHandler document(String identifier, Snippet... snippets) { return new RestDocumentationResultHandler(new RestDocumentationGenerator(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets)); }
由此看出要实现自定义片段只需要实现Snippet接口,并传入document方法就可以了,具体实现如下:
1: 在test的resources下建立org/springframework/restdocs/templates/asciidoctor文件夹,在这里新增一个ajax-example..snippet文件,在这个文件模版中能够通过一个map进行取值,而该map在下面的CustomSnippet的createModel方法生成的。常用语法,通过符号:{{ }} 进行取值,{{#headers}} {{value}} {{/headers}}进行遍历list。注意:::不能取没有的值,会报错
文件内容类似如下:
[source,http,options="nowrap"] ---- 示例1: $.ajax({ url:'{{path}}', dataType:'json', type:'json', data:{{data}}, success:function(data){ console.log(data) } }) 示例1: axios.post('{{path}}',{{data}}) .then((response){ console.log(response.data) }) ----
2:继承抽象类TemplatedSnippet,类名CustonSippet,实现其createModel方法具体实现如下:
@Override protected Map<String, Object> createModel(Operation operation) { Map map = new HashMap(); this.path = operation.getRequest().getUri().toString(); map.put("data",JSONObject.toJSONString(data)); map.put("path",path); return map; }
3:调用document方法的创建一个TemplatedSnippet示例,传入模版的名称。
document("{method-name}",requestParameters( parameterWithName("name").description("姓名") ,parameterWithName("address").description("地址") ,parameterWithName("phone").description("联系电话") ),relaxedResponseFields( fieldWithPath("app").type("String").description("app代码") ,fieldWithPath("address").type("String").description("地址") ,fieldWithPath("phone").type("String").description("电话") ,fieldWithPath("name").type("String").description("姓名") ),new CustomSnipet("ajax-example","ajax-example",(Map)params.toSingleValueMap()) )
这样在生成代码片段的时候就会生成自定义的代码片段了。
https://snailsdream.github.io/