Importing properties from an external file in Spring Boot

This article deals with using properties from an external location in a Spring Boot application.

Importing Properties in a nutshell

With earlier versions of Spring Boot, it was cumbersome to import additional properties or yaml files short of using application.properties and application.yml. You could use the spring.config.additional-location property, but you needed to set it pretty early and it was quite limited with the types of files that it could deal with.

Since Spring Boot 2.4.0 release, you can use the new spring.config.import property directly in your application.properties or application.yml files. Let’s see an example application.

We will use the following application.properties file:

spring.config.import=developer.properties

This file imports another file named developer.properties with extra properties:

app.title=Learning Spring Boot app.description=Working with properties file

And here is a sample Controller class which references these properties:

package com.example.testrest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
@RestController public class SampleController {
  @Value("${app.title}")
  private String appTitle;
  @Value("${app.description}") private String appDescription;
  @RequestMapping("/hello") public String hello() {
    return "Hello from " + appTitle + " " + appDescription;
  }
}

This example is available here: https://github.com/fmarchioni/masterspringboot/tree/master/properties/additional

Optional configurations

Config locations specified via spring.config.location and spring.config.import (introduced in the Spring Boot release 2.4.0) will no longer fail silently if the file or folder does not exist. If you want to import a location, but you don’t mind skipping it if it cannot be found, you should now prefix it with optional:

For example:

spring.config.location=optional:/etc/config/application.properties

This configuration file will import an application.properties file from /etc/config/ if it exists, and skip it if it does not.

If you want to treat all locations as optional you can set spring.config.on-not-found=ignore in SpringApplication.setDefaultProperties(…​) or with a system/environment variable.

You can even combine spring.config.import declarations with spring.config.activate.on-profile properties. For example, here we load prod.properties only if the prod profile is active:

spring.config.activate.on-profile=prod spring.config.import=prod.properties
Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon