java - 从 "allowableValues"中的数据库传递值?

标签 java spring swagger-2.0

我正在将 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/

相关文章:

yaml - 如何将对象数组定义为参数?

java - 如何将一副牌洗入两手

java - java中的合并映射恢复插入顺序

java - 使用 hibernate 4.0 和 spring 3.1.0.release 的事件监听器?

java - Spring MVC - 重定向后保留请求参数

java - 为 @ApiOperations 为 springfox swagger2 定义自定义 json 序列化器

java - 如何在 Linux 上配置 VSCode 使其在不同的项目中为 Gradle 应用不同的 JAVA_HOME?

java - 运行在 Appserver 中的 Spring Container 是否有单独的类加载器?

java - 两个 Controller 在 Spring Boot 中具有不同的最大文件大小

java - 更改 swagger-ui 中 java.sql.Time 的模型架构