Spring Environment backed by Typesafe Config

前端 未结 4 1671
庸人自扰
庸人自扰 2020-12-30 01:22

I want to use typesafe config (HOCON config files) in my project, which facilitate easy and organized application configuration. Currently I am using normal Java properties

4条回答
  •  执笔经年
    2020-12-30 01:42

    I think I came up with a slightly more idiomatic way than manually adding the PropertySource to the property sources. Creating a PropertySourceFactory and referencing that with @PropertySource

    First, we have a TypesafeConfigPropertySource almost identical to what you have:

    public class TypesafeConfigPropertySource extends PropertySource {
        public TypesafeConfigPropertySource(String name, Config source) {
            super(name, source);
        }
    
        @Override
        public Object getProperty(String path) {
            if (source.hasPath(path)) {
                return source.getAnyRef(path);
            }
            return null;
        }
    }
    

    Next, we create a PropertySource factory that returns that property source

    public class TypesafePropertySourceFactory implements PropertySourceFactory {
    
        @Override
        public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
            Config config = ConfigFactory.load(resource.getResource().getFilename()).resolve();
    
            String safeName = name == null ? "typeSafe" : name;
            return new TypesafeConfigPropertySource(safeName, config);
        }
    
    }
    

    And finally, in our Configuration file, we can just reference the property source like any other PropertySource instead of having to add the PropertySource ourselves:

    @Configuration
    @PropertySource(factory=TypesafePropertySourceFactory.class, value="someconfig.conf")
    public class PropertyLoader {
        // Nothing needed here
    }
    

提交回复
热议问题