读取yaml文件配置信息

yaml文件配置

model-type:
    config-map: {"422000011":"01","422000012":"02","422000013":"03","422000014":"04","422000015":"05","422000016":"06","422000017":"07","422000018":"08"}
    event-type-list:
      - eventType: "202400001"
        eventTypeName: "1111"
        aimmsEventType: "1"
      - eventType: "202400001"
        eventTypeName: "1111"
        aimmsEventType: "1"
    test-dd: "1234"

类文件

@PropertySource(value = {"classpath:application-static.yaml"},encoding = "utf-8",factory = YamlPropertyLoaderFactory.class)
@EnableConfigurationProperties(ModelTypeConfig.class)
@ConfigurationProperties(prefix = "model-type")
@Configuration
@Data
public class ModelTypeConfig{
    @ApiModelProperty(“")
    //@Value("${configMap}")
    private JSONObject configMap;

    @ApiModelProperty("")
    //@Value("${eventTypeList}")
    private List<EventTypeConfigNewDto> eventTypeList;

    private String testDd;

    @Data
    public static class EventTypeConfigNewDto {
        private String eventType;
        private String eventTypeName;
        private String aimmsEventType;
    }
}

遇到问题:ModelTypeConfig里的所有字段值都为null,只有加上@Value才可以读到值

问题原因:当前springboot版本里面@ConfigurationProperties默认配置properties文件,而暂时不支持默认导入yml文件(以上yml文件改用properties文件导入是可行不会出现null)

解决方案:通过重写框架默认DefaultPropertySourceFactory方法,使.yml文件装配成功

public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null){
            return super.createPropertySource(name, resource);
        }

        return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
    }
}

 

posted on 2024-01-09 09:42  LJD泊水  阅读(34)  评论(0编辑  收藏  举报