Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to provide default values for env variables in a properties file with apache-commons?

I'm using org.apache.commons:commons-configuration2:2.5 to read config parameters from a config file. In my application.properties, I want to specify default values for environment variables in case one of these has not been set, e.g. like so (similar as with Spring):

idp.username=${env:IDP_USERNAME:defaultUsername}

However, while setting the env variable works fine, specifying a default value like this is not working. Unfortunately, I can't find anything related to this in the commons-configuration2 documentation. Is this possible without explicitly checking for a missing value in the Java code? Does Spring Boot use a certain lib for this that I could also use? I don't want to bloat up my simple app with the Spring framework only to have this kind of configuration.

Simplified code example I'm currently using (here, I obviously could check each property I retrieve and replace it with a default, but I'd like to avoid this and handle it directly in the config file):

private void loadConfigFile() {
        logger.info("Attempting to load `application.properties`...");
        Configurations configBuilder = new Configurations();
        try {
            Configuration props = configBuilder.properties(new File("application.properties"));

            // application config
            this.conf = new Config();
            this.conf.setAPIEndpoint(props.getString("api.endpoint"));
            this.conf.setMaxConnections(props.getInt("api.maxConnections"));
            ...

            logger.info("Config successfully loaded!");
        } catch (Exception e) {
            logger.error("Could not load `application.properties`: {}", e.getMessage());
            System.exit(1);
        }
    }

Any suggestions?

like image 790
xJREB Avatar asked Oct 15 '22 14:10

xJREB


1 Answers

Commons Configuration provides a way to do custom interpolation. This answer shows an example. Your Lookup implementation would need to handle parsing everything past the prefix and then doing the lookup and providing the default value.

like image 109
Matt Berteaux Avatar answered Nov 02 '22 05:11

Matt Berteaux