application.properties and Configuration
application.properties and Configuration
Externalizing configuration is a core Spring idea. Keep settings out of your Java code so the same jar can run in development, staging, and production just by changing properties, environment variables, or profiles.
Common settings
The application.properties file at the root of the classpath holds key-value pairs. Boot reads them on startup and binds them to components.
server.port=8080
spring.application.name=groovygrails-hub
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=update
app.welcome.message=Welcome back!
Typed binding with @ConfigurationProperties
Group related properties into a class and bind them with @ConfigurationProperties. This converts strings into typed fields, so a typo in a property is a startup failure instead of a silent wrong value at runtime.
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String welcomeMessage;
// getters and setters
}
Profiles
Name a file application-<profile>.properties for environment-specific settings, then activate it with spring.profiles.active or the SPRING_PROFILES_ACTIVE environment variable. Overrides take a clear precedence order: command line, environment variables, profile files, then the base file.
Environment variables and secrets
Never hardcode secrets. Reference them from environment variables or a secrets manager, and keep database credentials, API keys, and passwords out of version control. Boot relaxes binding, so spring.datasource.password maps to the environment variable form naturally.
Precedence and debugging
When a setting is not what you expect, remember the precedence ladder and inspect the environment section of the Actuator endpoint /actuator/env to see every source and value. The ability to trace configuration is what makes externalized settings reliable.
Key Points
- Configuration lives in
application.properties, overridable by profiles and environment variables. @ConfigurationPropertiesbinds groups of properties to typed objects.- Use profiles for environment-specific settings.
- Keep secrets out of code and properties files.
- Trace effective values with Actuator's env endpoint.