Sprngboot2實戰之@PropertySource擴展

@PropertySource擴展

@PropertySource(value={"classpath:person.properties"}) //從指定屬性文件中讀取屬性

如上,@PropertySource只能讀取.properties文件到application中,但目前spring boot是默認支持application.yml作爲默認配置文件的,如何才能讀取自定義的.yml文件呢,如下步驟:

  1. 定義 YamlPropertySourceFactory

    public class YamlPropertySourceFactory implements PropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            Properties ymlProperties = factory.getObject();
            String propertyName = name != null ? name : resource.getResource().getFilename();
            return new PropertiesPropertySource(propertyName, ymlProperties);
        }
    }
    
    
  2. 配置@PropertySource

    @PropertySource(value = "classpath:person.yml",factory = YamlPropertySourceFactory.class)
    
    

之後就可以像使用properties一樣,使用yml文件了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章