Application Properties

Configuring Spring Boot applications

← Back to Index

Configuration Files

application.properties

# Server
server.port=8080
server.servlet.context-path=/api

# Database
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=user
spring.datasource.password=pass

# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# Logging
logging.level.root=INFO
logging.level.com.example=DEBUG

# Custom properties
app.name=My Application
app.max-connections=100

application.yml (Alternative)

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

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: user
    password: pass
  jpa:
    hibernate:
      ddl-auto: update

app:
  name: My Application
  max-connections: 100

Accessing Properties

@Value Annotation

@Component
public class MyService {

    @Value("${app.name}")
    private String appName;

    @Value("${app.max-connections:50}")  // With default
    private int maxConnections;

    @Value("${SERVER_PORT:8080}")  // Environment variable
    private int port;
}

@ConfigurationProperties (Recommended)

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {

    private String name;
    private int maxConnections;
    private Security security = new Security();

    public static class Security {
        private String secretKey;
        private long tokenExpiry;
        // getters/setters
    }

    // getters/setters
}

// application.yml
app:
  name: My App
  max-connections: 100
  security:
    secret-key: mySecretKey
    token-expiry: 3600000

Property Sources Priority

Spring Boot loads properties in this order (later overrides earlier):

  1. Default properties
  2. application.properties/yml in classpath
  3. application.properties/yml outside JAR
  4. Profile-specific properties
  5. Command line arguments
  6. Environment variables
# Override via command line
java -jar app.jar --server.port=9090

# Override via environment variable
export SERVER_PORT=9090
java -jar app.jar

Summary

  • application.properties: Key=value configuration
  • application.yml: YAML format (hierarchical)
  • @Value: Inject single properties
  • @ConfigurationProperties: Type-safe configuration
  • Environment variables: Override any property