天下脸皮共十分
我占八分

自定义YAML配置文件并读取

YAML:yet another mark language

定义yaml解析工厂

 package tech.ityoung.config;
 ​
 import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
 import org.springframework.core.env.PropertiesPropertySource;
 import org.springframework.core.env.PropertySource;
 import org.springframework.core.io.support.DefaultPropertySourceFactory;
 import org.springframework.core.io.support.EncodedResource;
 ​
 import java.io.IOException;
 import java.util.Properties;
 ​
 public class YmlConfigFactory extends DefaultPropertySourceFactory {
     @Override
     public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
         String sourceName = name != null ? name : resource.getResource().getFilename();
         if (!resource.getResource().exists()) {
             return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
             Properties propertiesFromYaml = loadYml(resource);
             return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
             return super.createPropertySource(name, resource);
        }
    }
 ​
     private Properties loadYml(EncodedResource resource) throws IOException {
         YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
         factory.setResources(resource.getResource());
         factory.afterPropertiesSet();
         return factory.getObject();
    }
 }

在@PropertiySource注解中指明文件名和工厂

 package tech.ityoung.config;
 ​
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.PropertySource;
 import org.springframework.stereotype.Component;
 ​
 @Component
 @PropertySource(value = {"classpath:test.yaml"},factory = YmlConfigFactory.class)
 public class YamlTest {
 ​
     @Value("${stephen.young.age}")
     private int age;
 ​
     @Bean("age")
     public Integer getAge() {
         return age;
    }
 }

自定义yaml配置文件

注意最终的属性跟冒号之间有一个空格

 stephen:
  young:
    age: 27
赞(2) 打赏
未经允许不得转载:Stephen Young » 自定义YAML配置文件并读取
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏