Spring Environment backed by Typesafe Config

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

    Laplie Anderson answer with some small improvements:

    • throw exception if resource not found
    • ignore path that contains [ and : characters

    TypesafePropertySourceFactory.java

    import java.io.IOException;
    
    import org.springframework.core.env.PropertySource;
    import org.springframework.core.io.support.EncodedResource;
    import org.springframework.core.io.support.PropertySourceFactory;
    
    import com.typesafe.config.Config;
    import com.typesafe.config.ConfigFactory;
    import com.typesafe.config.ConfigParseOptions;
    import com.typesafe.config.ConfigResolveOptions;
    
    public class TypesafePropertySourceFactory implements PropertySourceFactory {
    
      @Override
      public PropertySource createPropertySource(String name, EncodedResource resource)
          throws IOException {
        Config config = ConfigFactory
            .load(resource.getResource().getFilename(),
                ConfigParseOptions.defaults().setAllowMissing(false),
                ConfigResolveOptions.noSystem()).resolve();
    
        String safeName = name == null ? "typeSafe" : name;
        return new TypesafeConfigPropertySource(safeName, config);
      }
    }
    

    TypesafeConfigPropertySource.java

    import org.springframework.core.env.PropertySource;
    
    import com.typesafe.config.Config;
    
    public class TypesafeConfigPropertySource extends PropertySource {
      public TypesafeConfigPropertySource(String name, Config source) {
        super(name, source);
      }
    
      @Override
      public Object getProperty(String path) {
        if (path.contains("["))
          return null;
        if (path.contains(":"))
          return null;
        if (source.hasPath(path)) {
          return source.getAnyRef(path);
        }
        return null;
      }
    }
    

提交回复
热议问题