Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to transform .properties file in java like app.config in C#

I have debug.properties file with debug settings in our project. This file located in repo and each teamate should made changes in this one before debugging.

Can I modify this file based on some debug.template.properties file before build like xml transformation in C#?

like image 684
Dmitry Romashov Avatar asked Dec 02 '25 10:12

Dmitry Romashov


1 Answers

You can use cfg4j library and the following code:

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();
}
like image 175
Dmitry Romashov Avatar answered Dec 05 '25 01:12

Dmitry Romashov