随笔 - 160  文章 - 0  评论 - 13  阅读 - 42万

读取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   LJD泊水  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示