swagger版本:3.0
由于之前項目采用@ApiModelProperty對響應(yīng)屬性進行說明,但是由于dataType的屬性不規(guī)范,造成了swagger中的類型說明為object,所以跟蹤了一下swagger的注解解析過程。
ApiModelPropertyPropertyBuilder.class關(guān)鍵代碼
public void apply(ModelPropertyContext context) {
Optional<ApiModelProperty> annotation = empty();
if (context.getAnnotatedElement().isPresent()) {
annotation =
annotation.map(Optional::of)
.orElse(findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
}
if (context.getBeanPropertyDefinition().isPresent()) {
annotation = annotation.map(Optional::of).orElse(findPropertyAnnotation(
context.getBeanPropertyDefinition().get(),
ApiModelProperty.class));
}
if (annotation.isPresent()) {
ModelSpecification modelSpecification =
annotation.map(a -> {
if (!a.dataType().isEmpty()) {
// 關(guān)注點1:
return modelSpecifications.create(context.getOwner(), toType(context.getResolver()).apply(a));
}
return null;
})
.orElse(null);
Optional<ApiModelProperty> finalAnnotation = annotation;
context.getSpecificationBuilder()
.description(annotation.map(toDescription(descriptions)).orElse(null))
.readOnly(annotation.map(ApiModelProperty::readOnly).orElse(false))
.isHidden(annotation.map(ApiModelProperty::hidden).orElse(false))
//注意此處修改了Type屬性
.type(modelSpecification)
.position(annotation.map(ApiModelProperty::position).orElse(0))
.required(annotation.map(ApiModelProperty::required).orElse(false))
.example(annotation.map(toExample()).orElse(null))
.enumerationFacet(e -> e.allowedValues(finalAnnotation.map(toAllowableValues()).orElse(null)));
context.getBuilder()
.allowableValues(annotation.map(toAllowableValues()).orElse(null))
.required(annotation.map(ApiModelProperty::required).orElse(false))
.readOnly(annotation.map(ApiModelProperty::readOnly).orElse(false))
.description(annotation.map(toDescription(descriptions)).orElse(null))
.isHidden(annotation.map(ApiModelProperty::hidden).orElse(false))
.type(annotation.map(toType(context.getResolver())).orElse(null))
.position(annotation.map(ApiModelProperty::position).orElse(0))
.example(annotation.map(toExample()).orElse(null));
}
}
ApiModelProperties.class 關(guān)鍵代碼2
static Function<ApiModelProperty, ResolvedType> toType(final TypeResolver resolver) {
return annotation -> {
try {
//ApiModelProperty 的dataType 只能寫 全局限域名
return resolver.resolve(Class.forName(annotation.dataType()));
} catch (ClassNotFoundException e) {
// 如果找不到類對象,則會被覆蓋為Object類型
return resolver.resolve(Object.class);
}
};
}
建議 @ApiModelProperty 注解的dataType不寫,采用swagger默認的屬性說明