Custom configuration files - apinazo/booter GitHub Wiki

Overview

The app implements a demo of loading configurations from not standard files.

Loading custom configuration files

A Spring Boot app can be configured to load configuration files other than the default application and bootstrap. But in order to do so, an environment post processor must be defined. That class will:

  • Know the path to the custom configuration file or files to load.
  • Read them.
  • Convert their contents to a Spring property source.
  • Load the properties into the environment, as a resource, under a defined name/prefix.

Custom environment post processor

The way to load a custom configuration file is from an EnvironmentPostProccessor. Here is an example of one that loads a file named extra-config.yml into the environment.

public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {

    // Loads a configuration from a yml file.
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    private final String configFileName = "extra-config.yml";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        // Load the yml file looking for it everywhere in the classpath.
        Resource path = new ClassPathResource(configFileName);

        // Get all its properties.
        PropertySource<?> propertySource = loadYml(path);

        // Add them all to the environment, at the end of all the resources.
        environment.getPropertySources().addLast(propertySource);
    }

    private PropertySource<?> loadYml(Resource path) {
        if (!path.exists()) {
            throw new IllegalArgumentException("Resource " + path + " does not exist");
        }
        try {
            // Load the file and give the resource the prefix custom-resource.
            return this.loader.load("custom-resource", path).get(0);
        }
        catch (IOException ex) {
            throw new IllegalStateException(
                    "Failed to load yml configuration from " + path, ex);
        }
    }
}

Note that - as this is a totally custom implementation - it could load several configuration files at once or add support for properties files if the yml file is not found and so on.

Configuring the post processor

As noticed, the CustomEnvironmentPostProcessor is not a Spring bean. Obviously, the configuration files must be loaded before the context and environment are ready. Thus the post processor must be registered before that. This is done in the spring.factories file this way:

# Custom environment post processors.
# This one loads additional configuration from a extra-config.yml file. Application start will fail if not found.
org.springframework.boot.env.EnvironmentPostProcessor=es.apinazo.booter.configuration.CustomEnvironmentPostProcessor