由Typesafe Config支持的Spring Environment


问题内容

我想在我的项目中使用typesafe config(HOCON
config文件),这有助于简单而有组织的应用程序配置。目前,我正在使用普通的Java属性文件(application.properties),并且在大型项目上很难处理。

我的项目是Spring MVC(不是Spring Boot项目)。有没有一种方法可以支持我的Spring
Environment(我将注入到我的服务中)由typesafe config支持。这不应该阻止我现有的环境用法@Value@Autowired Environment例如注释等。

如何以最小的努力和对代码的更改来做到这一点。

这是我当前的解决方案:寻找其他更好的方法

@Configuration
public class PropertyLoader{
    private static Logger logger = LoggerFactory.getLogger(PropertyLoader.class);

    @Bean
    @Autowired
    public static PropertySourcesPlaceholderConfigurer properties(Environment env) {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();

        Config conf = ConfigFactory.load();
        conf.resolve();
        TypesafePropertySource propertySource = new TypesafePropertySource("hoconSource", conf);

        ConfigurableEnvironment environment = (StandardEnvironment)env;
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addLast(propertySource);
        pspc.setPropertySources(propertySources);

        return pspc;
    }
}

class TypesafePropertySource extends PropertySource<Config>{
    public TypesafePropertySource(String name, Config source) {
        super(name, source);
    }

    @Override
    public Object getProperty(String name) {
        return this.getSource().getAnyRef(name);
    }
}

问题答案:

我想我想出了一种比手动添加PropertySource到属性源更惯用的方法。创建一个PropertySourceFactory并引用@PropertySource

首先,我们TypesafeConfigPropertySource与您拥有的几乎相同:

public class TypesafeConfigPropertySource extends PropertySource<Config> {
    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;
    }
}

接下来,我们创建一个PropertySource 工厂 ,该 工厂 返回该属性源

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);
    }

}

最后,在我们的配置文件中,我们可以像其他任何属性一样引用属性源,PropertySource而不必自己添加PropertySource:

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