您的位置:首页 > 其它

Swagger除了注解方式之外自定义添加接口,额外定义接口

2018-01-29 15:38 435 查看
一、业务场景

 集成swagger框架之后,在代码上添加swagger注解即可生成api接口文档,在大多数情况下都适用。但除此之外我们还有其他的一些场景:

 1.非springMvc注解暴露接口,无法通过这种注解方式生成api接口文档

 2.引入了其他jar包,jar包里暴露了接口,但没有在接口上添加swagger注解,我们要为其生成api接口文档

3.jar包引入的接口,并且使用了swagger注解,但你需要重新定制接口说明。

 4.类似的其他限制场景...

二、自定义swagger接口

新建java类,并注册为spring组件,实现ApiListingScannerPlugin接口,重写apply方法。将自定义的接口排列成数组传入即可。
以下为自定义/oauth/token的接口例子。
@Component
public class SwaggerAddtion implements ApiListingScannerPlugin {
@Override
public List<ApiDescription> apply(DocumentationContext documentationContext) {
return new ArrayList<ApiDescription>(
Arrays.asList(
new ApiDescription(
"/oauth/token", //url
"UserToken", //描述
Arrays.asList(
new OperationBuilder(

4000
new CachingOperationNameGenerator())
.method(HttpMethod.POST)//http请求类型
.produces(Sets.newHashSet(MediaType.APPLICATION_JSON_VALUE))
.summary("获取token")
.notes("获取token")//方法描述
.tags(Sets.newHashSet("Token"))//归类标签
.parameters(
Arrays.asList(
new ParameterBuilder()
.description("oauth2鉴权方式,如password")//参数描述
.type(new TypeResolver().resolve(String.class))//参数数据类型
.name("grant_type")//参数名称
.defaultValue("password")//参数默认值
.parameterType("query")//参数类型
.parameterAccess("access")
.required(true)//是否必填
.modelRef(new ModelRef("string")) //参数数据类型
.build(),
new ParameterBuilder()
.description("用户名")
.type(new TypeResolver().resolve(String.class))
.name("username")
.parameterType("query")
.parameterAccess("access")
.required(true)
.modelRef(new ModelRef("string")) //<5>
.build(),
new ParameterBuilder()
.description("密码")
.type(new TypeResolver().resolve(String.class))
.name("password")
.parameterType("query")
.parameterAccess("access")
.required(true)
.modelRef(new ModelRef("string")) //<5>
.build()
))
.build()),
false)));
}

@Override
public boolean supports(DocumentationType documentationType) {
return DocumentationType.SWAGGER_2.equals(documentationType);
}
}三、运行效果



四、总结。

上面演示了自定义swagger接口的做法,结合实际场景,我们可以添加自己想添加的接口。

结合swagger配置过滤一些不必要的接口,可以实现重新定制接口说明。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐