application.yml and profiles

Spring Boot · lesson 7 of 39 · 4 min read

Externalise settings, layer them per environment, and override anything at startup.

Open this lesson in the learning hub

Key points

  • Put settings in src/main/resources/application.yml. YAML nests, so it stays readable.
  • A profile is a named environment. Activate with SPRING_PROFILES_ACTIVE=prod or --spring.profiles.active=prod.
  • application-prod.yml is loaded on top of application.yml; matching keys win.
  • Inside one file, split documents with --- and gate them with spring.config.activate.on-profile.
  • Later sources beat earlier ones: command-line args > env vars > profile file > base file.
  • Never commit secrets. Reference an env var with ${DB_PASSWORD} and set it outside the repo.

Example

# application.yml - shared defaults
spring:
  application:
    name: shop-service
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
    password: ${DB_PASSWORD}       # from the environment
  jpa:
    open-in-view: false            # turn this off; it hides lazy loading bugs

server:
  port: 8080

shop:
  currency: EUR
  max-items-per-order: 20

---
# Only applied when the 'prod' profile is active
spring:
  config:
    activate:
      on-profile: prod
  jpa:
    show-sql: false

logging:
  level:
    org.springframework.web: WARN

One config file, per-profile overlays, and env vars that win at deploy time.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.