zoukankan      html  css  js  c++  java
  • springboot2中@ConfigurationProperties装载yml文件的时候调取出现值为null的解决办法

    程序配置:springboot2,Java8

    @Configuration
    @Data
    @ConfigurationProperties(prefix = "person")
    @PropertySource(value = "classpath:content.yml", encoding = "UTF-8")
    public class SourceConfig {
        
        private String name;
        private String age;
        private String address;
    }

    yml文件:

    person:
      name: hhhh
      age: 20
      address: 北京

    以上是我一开始的配置,使用lombok的@Data注解自动生成get,set等方法,但是这种情况下,测试调用sourceConfig为null,主要参考了stackflow的办法,

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

    解决办法:

    @PropertySource(value = "classpath:content.yml", encoding = "UTF-8", factory = YamlPropertyLoaderFactory.class)
    
    import org.springframework.boot.env.YamlPropertySourceLoader;
    import org.springframework.core.env.PropertySource;
    import org.springframework.core.io.support.DefaultPropertySourceFactory;
    import org.springframework.core.io.support.EncodedResource;
    import java.io.IOException;
    
    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);
        }
    }
    

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

    看了stackflow的解答,在别人帮助下修改解决问题的

    stackflow的该问题解答链接:https://stackoverflow.com/questions/21271468/spring-propertysource-using-yaml

     我修改了他里面YamlPropertyLoaderFactory方法最后一行的返回值,他那个方法我编译的时候会报错~

  • 相关阅读:
    template
    open File Browser in shell
    自定义模板类型vs模板类型自动推测
    protobuffer
    多重继承&虚继承
    What I'm Researching
    JobTracker和TaskTracker
    MapReduce
    How To Use Google Flags
    Frequently Used Shell Commands
  • 原文地址:https://www.cnblogs.com/cg-bestwishes/p/11925802.html
Copyright © 2011-2022 走看看