是否可以在Java中转换.properties文件,如在C#中的app.config

时间:2016-09-06 10:06:47

标签: java c# config-transformation

我的项目中有调试设置的debug.properties文件。这个文件位于repo中,每个同伴都应该在调试之前对这个进行更改。

我可以在构建像C#中的xml转换之前基于某个debug.template.properties文件修改此文件吗?

1 个答案:

答案 0 :(得分:1)

您可以使用cfg4j库和以下代码:

private ConfigurationProvider configureProvider() {
    ClassLoader classLoader = getClass().getClassLoader();
    String envPath = classLoader.getResource("properties").getPath();
    Path localPropertiesFilePath = Paths.get(envPath, "local.properties");
    Path basePropertiesFilePath = Paths.get(envPath, "base.properties");

    if (!Files.exists(localPropertiesFilePath)) {
        try {
            Files.createFile(localPropertiesFilePath);
        }
        catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    ConfigFilesProvider localConfigFilesProvider =
            () -> Collections.singletonList(localPropertiesFilePath);
    ConfigFilesProvider baseConfigFilesProvider =
            () -> Collections.singletonList(basePropertiesFilePath);

    ConfigurationSource local = new FilesConfigurationSource(localConfigFilesProvider);
    ConfigurationSource base = new FilesConfigurationSource(baseConfigFilesProvider);
    // If you have 'some' property in base and local files - it takes from local
    ConfigurationSource mergedSource = new MergeConfigurationSource(base, local);

    Environment environment = new ImmutableEnvironment(envPath);

    return new ConfigurationProviderBuilder()
            .withConfigurationSource(mergedSource)
            .withEnvironment(environment)
            .build();
}