我正在将 Swagger 版本 2 与 Java Spring 结合使用。我已经声明了一个属性,它工作正常,并生成一个我分配的值的下拉列表。
@ApiParam(value = "Pass any one Shuttle provider ID from the list", allowableValues = "1,2,3,4,10")
private Long hotelId;
现在,我需要一种方法来填充此列表,该列表从我的数据库传入 allowableValues
,因为它可以是随机列表也可以是大量数据。如何在此 allowableValues
中动态分配数据库中的值列表?
最佳答案
这个问题有点老了,我也遇到了同样的问题,所以想在这里添加,这可能会对某些人有所帮助。
//对于ApiModelProperty
@ApiModelProperty(required = true, allowableValues = "dynamicEnum(AddressType)")
@JsonProperty("type")
private String type;
创建了一个实现 ModelPropertyBuilderPlugin 的组件
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class ApiModelPropertyPropertyBuilderCustom implements ModelPropertyBuilderPlugin {
private final DescriptionResolver descriptions;
@Autowired
public ApiModelPropertyPropertyBuilderCustom(DescriptionResolver descriptions) {
this.descriptions = descriptions;
}
public void apply(ModelPropertyContext context) {
try {
AllowableListValues allowableListValues = (AllowableListValues) FieldUtils.readField(context.getBuilder(),
"allowableValues", true);
if(allowableListValues!=null) {
String allowableValuesString = allowableListValues.getValues().get(0);
if (allowableValuesString.contains("dynamicEnum")) {
String yourOwnStringOrDatabaseTable = allowableValuesString.substring(allowableValuesString.indexOf("(")+1, allowableValuesString.indexOf(")"));
//Logic to Generate dynamic values and create a list out of it and then create AllowableListValues object
context.getBuilder().allowableValues(allowableValues);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean supports(DocumentationType delimiter) {
return SwaggerPluginSupport.pluginDoesApply(delimiter);
}
}
与 ApiParam 类似,我们可以创建将实现 ParameterBuilderPlugin 的组件
@Override
public void apply(ParameterContext context) {
@SuppressWarnings("Guava") final Optional<ApiParam> apiParam =
context.resolvedMethodParameter().findAnnotation(ApiParam.class);
if (apiParam.isPresent()) {
final String allowableValuesString = apiParam.get().allowableValues();
//Your logic here
context.parameterBuilder().allowableValues(allowableValues);
}
}
关于java - 从 "allowableValues"中的数据库传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38843911/