Externalized Configuration in Spring

Spring comes with excellent support for externalized configuration. This allows you to have sensible defaults checked into your source code repository, while providing a plethora of options for setting properties that shouldn’t be checked in (account credentials) or can’t be checked in (specification of active profiles):

  • OS environment variables
  • Profile specific application properties outside your jar (application-{profile}.properties or application-{profile}.yml)
  • Profile specific application properties packaged in your jar (application-{profile}.properties or application-{profile}.yml)
  • Application properties outside your jar (application.properties or application.yml)
  • Application properties packaged in your jar (application.properties or application.yml)

But if you’re deploying to an application server, then there is a little tweak that you’ll need to keep in your back pocket - changing the spring.config.name from application to something else in code. This will let you add a centralized configuration directory to your application server classpath for all your deployed web applications, where setting spring.config.name by environment variable, command line options or JNDI don’t work).

Personally, I like using the org.springframework.boot.builder.SpringApplicationBuilder to change the spring.config.name to myApp:

app = new SpringApplicationBuilder(Application.class)
    .properties("spring.config.name=myApp")
    .build()
    .run();

But, it can can also be done with the standard org.springframework.boot.SpringConfiguration.

app = new SpringApplication(Application.class);
Properties props = new Properties();
props.setProperty("spring.config.name","myApp");
app.setDefaultProperties(props);
app.run();

It is also possible to externalize the configuration with org.springframework.context.annotation.PropertySource, but this forgoes some application properties magic:

  • PropertySource does not support YAML
  • PropertySource does not have profile support
  • You override properties with application properties while you define all properties with PropertySource (application properties uses the value from the file with the highest priority, while PropertySource uses the file with the highest priority).
  • Maven plugin adds the project.build.directory to the application properties search list (spring.config.location), where developers can easily specify values while keeping them out of source control.