Skip to content

6.3.1 Defining profile-sprcific properties

One way to define profile-specific properties is to create yet another YAML or properties file containing only the properties for production. The name of the file should follow this convention: application-{profile name}.yml or application-{profile name} .properties. Then you can specify the configuration properties appropriate to that profile. For example, you could create a new file named application-prod.yml that contains the following properties:

yaml
spring:
  datasource:
    url: jdbc:mysql://localhost/tacocloud
    username: tacouser
    password: tacopassword
logging:
  level:
    tacos: WARN

Another way to specify profile-specific properties works only with YAML configuration. It involves placing profile-specific properties alongside nonprofiled properties in application.yml, separated by three hyphens and the spring.profiles property to name the profile. When applying the production properties to application.yml in this way, the entire application.yml would look like this:

yaml
logging:
  level:
    tacos: DEBUG

---
spring:
  profiles: prod

  datasource:
    url: jdbc:mysql://localhost/tacocloud
    username: tacouser
    password: tacopassword

logging:
  level:
    tacos: WARN

As you can see, this application.yml file is divided into two sections by a set of triple hyphens (---). The second section specifies a value for spring.profiles, indicating that the properties that follow apply to the prod profile. The first section, on the other hand, doesn’t specify a value for spring.profiles. Therefore, its properties are common to all profiles or are defaults if the active profile doesn’t otherwise have the properties set.

Regardless of which profiles are active when the application runs, the logging level for the tacos package will be set to DEBUG by the property set in the default profile. But if the profile named prod is active, then the logging.level.tacos property will be overridden with WARN. Likewise, if the prod profile is active, then the data source properties will be set to use the external MySQL database.

You can define properties for as many profiles as you need by creating additional YAML or properties files named with the pattern application-{profile name}.yml or application-{profile name}.properties. Or, if you prefer, type three more dashes in application.yml along with another spring.profiles property to specify the profile name. Then add all of the profile-specific properties you need. Although there’s no benefit to either approach, you might find that putting all profile configurations in a single YAML file works best when the number of properties is small, whereas distinct files for each profile is better when you have a large number of properties.

Released under the MIT License.