Configuring AndHow

How to configure AndHow before AndHow configures you(r application)


-- This page is not complete and relates to best practices for 0.4.2 and beyond (not 0.4.1) --


AndHow initializes itself automatically as soon as the first Property value is accessed. For instance:

public class HelloWorld {

private static final StrProp NAME = StrProp.builder().build();


public static void main(String[] args) {

System.out.println("Hello, " + NAME.getValue()); // <-- Causes initialization

}

}

NAME.getValue() forces AndHow to go through its initialization so it can provide the configured value. A core guarantee of AndHow is that it is immutable once initialized, so any attempt to modify AndHow's configuration after a value is read with throw a RuntimeException. How can you be sure your code to configure AndHow happens before the first property value is read?

First, why would an application need to configure AndHow? There are several possible reasons:

  • To pass in command-line arguments

  • To load Property values from a classpath properties file other than andhow.properties (need example)

  • To load Property values from a properties file on the filesystem (non-classpath) - Example (0.4.1 example - out of date)

  • To add, remove or reorder the Loaders or configure them

  • To set fixed values for some Properties (mostly done for testing)

Lets start with a common need and simplest example: Passing in command-line arguments.

AndHow can load values from most configuration sources automatically, however, it has no way to intercept the command line arguments passed to the main method - the application has to help. Here is modified version of HelloWorld, updated to load from the command line:

public class HelloWorld {

private static final StrProp NAME = StrProp.builder().build();


public static void main(String[] args) {

AndHow.findConfig().setCmdLineArgs(args); // <-- Pass cmd-line args to AndHow


System.out.println("Hello, " + NAME.getValue());

}

}

Configuring AndHow at an Application Entry Point

The simplest way to ensure AndHow configuration happens before Properties are accessed is to have a well defined Entry Point. Applications that start via the main() method, run in a container or a controlled environment (like an AWS Lambda) have easy to identify entry points. Utility libraries that are imported into an application generally do not.

In the above example, we know that the only entry point is via the main() method, so it is safe to configure AndHow at the top of that method.

...Details about AndHow.findConfig()...

Configuring AndHow via AndHowInit

For more complex applications, it is easier and safer to use the AndHowInit interface to configure AndHow.