1

Using Apache Commons Configurations 1.9, how to avoid ConfigurationException upon loading a configuration file if the provided file cannot be found?

The Spring app context resembles:

<bean name="foo.config" class="org.apache.commons.configuration.PropertiesConfiguration" init-method="load">
    <property name="fileName" value="foo.properties" />
</bean>

However my config file is optional, so I want to make sure the application starts correctly even the file doesn't exist.

How can I achieve this with Commons Configurations? A FactoryBean works, but is there another way?

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • 1
    @Dime I wrote my own factory bean at the end. I kind of remember I found a apache-common-configuration spring integration project at that time which contains something similar, but as that project was long-unmaintained so I gave up. I suspect situation may have changed with Common Config 2 was out but I haven't had chance to take further look. – Adrian Shum Apr 27 '17 at 01:13

1 Answers1

3
if (!file.exists()) return new PropertiesConfiguration();

Or using try/catch syntax using an XML configuration:

import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;

public class Workspace {

  private final XMLConfiguration mConfig;

  public Workspace() {
    final var configs = new Configurations();
    XMLConfiguration config;
  
    try {
      config = configs.xml( "filename.xml" );
    } catch( final Exception e ) {
      config = new XMLConfiguration();
    }
  
    mConfig = config;
  }

Using a regular properties configuration will work the same way.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
r33tnup
  • 319
  • 2
  • 9