SpringBoot引入自定义yml资源文件

4,749 阅读2分钟

直接使用application.yml命名

  • 如果放在classpath中,使用springboot默认资源文件的命名application.yml,springboot启动时会自动将资源文件加载带容器中,这样的话只需要一个自定义的前缀,去区分是自定义的配置项

  • 而且springboot支持将配置文件中的内容注入到spring的bean中。

    @Component
    @ConfigurationProperties(prefix = "config")
    @Data
    public class ConfigProperty implements Serializable {
        private static final long serialVersionUID = -6817721126868801771L;
    
        private Map<String, Map<String, Map<String, String>>> maps;
    
    }
    
  • 如果要在容器中使用的话,可以直接注入这个类,或者@value注解使用配置某个属性值

使用自定义命名的yml文件

  • 如何注入的是.property文件,只需要添加注解标识自定义文件的路径,就可以实现和使用springboot默认文件命名的功能。

    @Component
    @ConfigurationProperties(prefix = "config")
    @PropertySource(value = "classpath:config-validate.yml", encoding = "utf-8")
    @Data
    public class ConfigProperty implements Serializable {
        private static final long serialVersionUID = -6817721126868801771L;
    
        private Map<String, Map<String, Map<String, String>>> maps;
    
    }
    
  • 但是如果注入的是.yml文件,按照上面这种方式会出现问题。使用@PropertySource注解注入的资源文件默认是使用DefaultPropertySourceFactory进行加载解读的,这个类中默认是建立ResourcePropertySource去解析资源文件,但是这个类是用来解析.property文件,用这个类来解析.yml文件不能得到正确的内容。

    public class DefaultPropertySourceFactory implements PropertySourceFactory {
    
    	@Override
    	public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
    		return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
    	}
    
    }
    
  • 如果想要解析.yml文件需要自己定义一个解析yml文件的解析类,并在@PropertySource注解中进行引用

    public class ConfigParamFactory extends DefaultPropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            if (resource == null) {
                return super.createPropertySource(name, null);
            }
            List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
            return sources.get(0);
        }
    }
    
    @Component
    @ConfigurationProperties(prefix = "config")
    @PropertySource(value = "classpath:config-validate.yml", encoding = "utf-8", factory = ConfigParamFactory.class)
    @Data
    public class ConfigProperty implements Serializable {
        private static final long serialVersionUID = -6817721126868801771L;
    
        private Map<String, Map<String, Map<String, String>>> maps;
    
    }