6

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?

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
xJREB
  • 333
  • 5
  • 10
  • Why are you reading application.properties with commons configuration? This can easily be done with Spring Boot? – Simon Martinelli May 28 '19 at 14:01
  • 1
    As specified in the question, I don't use Spring Boot in this specific application and would like to avoid it. The file is just named `application.properties` for convenience. – xJREB May 28 '19 at 14:08

1 Answers1

3

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.

Matt Berteaux
  • 763
  • 4
  • 12