通过@ConfigurationProperties

时间:2018-07-31 10:37:44

标签: spring-boot yaml

我正在使用@ConfigurationProperties将配置属性从YAML文件绑定到Java属性类。

在属性类中有以下字段:

private List<Map<String, Map<String, String>>> actionsBeforeIndexing;

它在YAML中的外观如下:

actionsBeforeIndexing:
  - testAction:
    param: value

这有效。但是我也希望能够定义这样的空列表(不带参数的操作):

actionsBeforeIndexing:
  - testAction

甚至是这样(不执行任何操作):

actionsBeforeIndexing:

当我尝试使用这些空列表时,会出现以下异常:

Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.List<java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.lang.String>>>]

如何使它工作?甚至没有定义列表,也许有办法强制像列表一样解析这个YAML选项吗?

1 个答案:

答案 0 :(得分:0)

不太好,但是可行的解决方案是创建两个类型转换器:

/**
 * Convert empty property in YAML to empty Map.
 *
 * parses this:
 *
 *   actionsBeforeIndexing:  -->  Map<String, Map<String, String>>
 */
@Component
@ConfigurationPropertiesBinding
public class ActionListPropertyConverter implements Converter<String, Map<String, Map<String, String>>> {

    @Override
    public Map<String, Map<String, String>> convert(String source) {

        Map<String, Map<String, String>> map = new HashMap<>();

        if (StringUtils.hasText(source)) {
            /*
             * parse action name without ending colon:
             *
             *   actionsBeforeIndexing:
             *   - testAction  -->  Map<String, String>
             */
            map.put(source, new HashMap<>());
        }

        return map;
    }
}

/**
 * Convert empty property in YAML to empty Map.
 *
 * parses this:
 *
 *   actionsBeforeIndexing:
 *   - testAction:  -->  Map<String, String>
 */
@Component
@ConfigurationPropertiesBinding
public class ActionParameterPropertyConverter implements Converter<String, Map<String, String>> {

    @Override
    public Map<String, String> convert(String source) {
        return new HashMap<>();
    }
}