Spring Environment backed by Typesafe Config

前端 未结 4 1684
庸人自扰
庸人自扰 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:44

    You create a PropertySource class as follows, it is similar to yours with the difference that you have to return the value or null and not let the lib throw a missing exception

    public class TypesafeConfigPropertySource extends PropertySource {
    
        private static final Logger LOG = getLogger(TypesafeConfigPropertySource.class);
    
        public TypesafeConfigPropertySource(String name, Config source) {
            super(name, source);
        }
    
        @Override
        public Object getProperty(String name) {
            try {
                return source.getAnyRef(name);
            } catch (ConfigException.Missing missing) {
                LOG.trace("Property requested [{}] is not set", name);
                return null;
            }
        }
    }
    

    Second step is to define a bean as follows

        @Bean
        public TypesafeConfigPropertySource provideTypesafeConfigPropertySource(
            ConfigurableEnvironment env) {
    
            Config conf = ConfigFactory.load().resolve();
            TypesafeConfigPropertySource source = 
                              new TypesafeConfigPropertySource("typeSafe", conf);
            MutablePropertySources sources = env.getPropertySources();
            sources.addFirst(source); // Choose if you want it first or last
            return source;
    
        }
    

    In cases where you want to autowire properties to other beans you need to use the annotation @DependsOn to the propertysource bean in order to ensure it is first loaded

    Hope it helps

提交回复
热议问题