application.properties and application.yml

2 minute read

Spring Boot’s configuration lives in application.properties or application.yml. This chapter covers both formats, custom properties, type-safe configuration, and externalized configuration.


Properties vs YAML

application.properties

server.port=8081
spring.datasource.url=jdbc:postgresql://localhost:5432/bookstore
spring.datasource.username=admin
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

application.yml

server:
  port: 8081

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/bookstore
    username: admin
    password: secret
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
Feature .properties .yml
Readability Flat ✅ Hierarchical
Lists Comma-separated ✅ YAML syntax
Comments # #
IDE support ✅ ✅
Indentation errors None Possible

Choose one format and stick with it. YAML is more popular in modern projects.


Common Configuration Properties

# Server
server:
  port: 8080
  servlet:
    context-path: /api

# Database
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
  h2:
    console:
      enabled: true
      path: /h2-console

# JPA
  jpa:
    hibernate:
      ddl-auto: create-drop    # create-drop | update | validate | none
    show-sql: true
    properties:
      hibernate:
        format_sql: true

# Logging
logging:
  level:
    root: INFO
    com.bookstore: DEBUG
    org.hibernate.SQL: DEBUG

@Value — Injecting Properties

@RestController
public class InfoController {

    @Value("${app.name:Bookstore API}")      // with default value
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    @Value("${server.port}")
    private int port;

    @GetMapping("/info")
    public Map<String, Object> info() {
        return Map.of("name", appName, "version", appVersion, "port", port);
    }
}
app:
  name: Bookstore API
  version: 1.0.0

@ConfigurationProperties(prefix = "app")
public record AppProperties(
    String name,
    String version,
    String contactEmail,
    Security security
) {
    public record Security(
        String jwtSecret,
        long jwtExpirationMs,
        List<String> allowedOrigins
    ) {}
}
app:
  name: Bookstore API
  version: 1.0.0
  contact-email: admin@bookstore.com
  security:
    jwt-secret: my-super-secret-key
    jwt-expiration-ms: 86400000
    allowed-origins:
      - http://localhost:3000
      - https://bookstore.com

Enable it:

@SpringBootApplication
@ConfigurationPropertiesScan
public class BookstoreApiApplication { }

Use it:

@Service
public class AuthService {

    private final AppProperties appProperties;

    public AuthService(AppProperties appProperties) {
        this.appProperties = appProperties;
    }

    public String generateToken() {
        String secret = appProperties.security().jwtSecret();
        long expiration = appProperties.security().jwtExpirationMs();
        // ...
    }
}

@ConfigurationProperties is preferred over @Value — type-safe, refactorable, testable.


Configuration Hierarchy (Priority)

Spring Boot loads config from multiple sources (highest priority wins):

1. Command line args              --server.port=9090
2. Java system properties         -Dserver.port=9090
3. OS environment variables       SERVER_PORT=9090
4. application-{profile}.yml      application-prod.yml
5. application.yml                application.yml
6. @PropertySource annotations
7. Default properties
# Override at runtime
java -jar app.jar --server.port=9090
SERVER_PORT=9090 java -jar app.jar
java -Dserver.port=9090 -jar app.jar

Environment Variables Mapping

Spring Boot maps env vars automatically:

Property Environment Variable
server.port SERVER_PORT
spring.datasource.url SPRING_DATASOURCE_URL
app.security.jwt-secret APP_SECURITY_JWT_SECRET

Rule: uppercase, dots → underscores, hyphens → underscores.


Common Mistakes

Mistake Fix
YAML indentation error Use 2 spaces, no tabs
Both .properties and .yml exist Pick one — YAML takes precedence for same property
Hardcoding secrets Use env vars: ${DB_PASSWORD}
Missing @ConfigurationPropertiesScan Required to enable @ConfigurationProperties records

Key Takeaways

  1. Use YAML for readability, .properties for simplicity.
  2. @ConfigurationProperties > @Value — type-safe, testable, groupable.
  3. Config hierarchy: command line > env vars > profile-specific > default.
  4. Never hardcode secrets — use environment variables.
  5. Spring maps server.port ↔ SERVER_PORT automatically.

What’s Next?

Next: Spring Boot Profiles — dev, staging, production configurations.

Updated: