springboot解析yml(不利用注解实现)

  这几天在写一个只有静态变量和静态方法的的工具类,但是这个工具类又需要获取yml中的配置信息。

  然后spring的bean的实例化顺序是静态代码块->构造函数->setter->InitializingBean中的afterPropertiesSet()等。而且spring的注入方案是从对象入手进行注入的,所以无法进行注入,因此我们需要返璞归真。使用直接解析的方案进行yml数据获取。

 YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("application-cos.yml"));
        Properties properties = yaml.getObject();
        accessKey = (String) properties.get("cos.tengxun.accessKey");
        secretKey = (String) properties.get("cos.tengxun.secretKey");

这个方案不需要使用snakeymal因为springboot-starter中的snakeyaml有点奇葩,具体原因还没有研究,只知道少了点类(有点像阉割版的)。因此我选择不引入新的依赖。直接利用springboot的配置管理进行获取就好了。如果不是使用spring的框架。利用我们常用的hutool工具包也能完成当前任务。

猜你喜欢

转载自blog.csdn.net/mathew_leung/article/details/104204577