SpringBoot使用yaml作为配置文件之坑

背景:最近搞新项目,重新搭建一套基于SpringBoot的开发框架。

问题的由来是我在进行一个dao单元测试时,一直失败,报错信息大概是“生成dataSource时maxActive属性不能为0”。基于以往的经验,应该是配置属性没有成功加载。排查由@ConfigurationProperties注解注释的配置属性类时,application.yml中的属性怎么注入不进来。

查看debug日志,发现很奇怪的一行日志

Skipped (empty) config file 'file:/E:/workspace/union-service/union-service-dao/target/test-classes/application.yml' (classpath:/application.yml)

明明不是空的!怀疑文件名不对,确认并重试了几次,仍然不行,只能调试了。

调试到了PropertySourcesLoader这个类

public PropertySource<?> load(Resource resource, String group, String name,
  String profile) throws IOException {
if (isFile(resource)) {
  String sourceName = generatePropertySourceName(name, profile);
  for (PropertySourceLoader loader : this.loaders) {
  if (canLoadFileExtension(loader, resource)) {
    PropertySource<?> specific = loader.load(sourceName, resource,
      profile);
    addPropertySource(group, specific, profile);
    return specific;
  }
  }
}
return null;
}

YamlPropertySourceLoader类的load方法:


@Override
public PropertySource<?> load(String name, Resource resource, String profile)
  throws IOException {
if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
  Processor processor = new Processor(resource, profile);
  Map<String, Object> source = processor.process();
  if (!source.isEmpty()) {
  return new MapPropertySource(name, source);
  }
}
return null;
}

查找" org.yaml.snakeyaml.Yaml"类,如果不存在,就返回null。我的项目代码修改倒也简单,添加snakeyaml的依赖即可。

但是SpringBoot代码执行到这里,说明已经存在resource文件,因为没有解析yaml的类跳过去,再去找其他适合的配置文件,也说的过去,可是为啥不能打个日志提示一下粗心又顽强的码农们呢?

感觉修改一下比较好,类似这样:

@Override
public PropertySource<?> load(String name, Resource resource, String profile)
  throws IOException {
if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
  Processor processor = new Processor(resource, profile);
  Map<String, Object> source = processor.process();
  if (!source.isEmpty()) {
  return new MapPropertySource(name, source);
  }
} else {
  logger.warn("Found " + name + " while lacking of snakeyaml");
}
return null;
}

相关issue已在github提交给spring boot。

转载于:https://my.oschina.net/bfleeee/blog/879209

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值