Profiles and Property Sources
Profiles and Property Sources
Applications behave differently per environment: a dev setup uses H2 in memory, production uses a managed database and stricter logging. Spring addresses this with profiles for beans and property sources for configuration values.
Profiles gate beans
Annotate beans with @Profile("dev") and they exist only when that profile is active. Activate profiles with spring.profiles.active, a program argument, or the environment variable. You can also annotate entire @Configuration classes so a whole set of beans activates together.
@Configuration
@Profile("dev")
public class DevDataSourceConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
}
Property sources
Spring collects configuration values from many sources: command-line arguments, environment variables, JVM system properties, profile-specific property files, and the base application.properties, in a well-defined precedence order. Later sources win. The Environment abstraction exposes all of it through a single API.
Comparing mechanisms
Think of @Value("${app.retry.count}") for individual values and @ConfigurationProperties for typed groups. Profiles change which beans and property files are active; property sources supply the values themselves. Together they let the same classes adapt to any environment.
Safe defaults
Only put environment-independent defaults in the base properties file, and read the rest from profiles or the environment. Secrets never belong in property files committed to a repository; resolve them from environment variables or a secret manager at runtime.
Key Points
- Profiles activate environment-specific beans and property files.
- Property sources follow a precedence order that later wins.
- Use
@Profileon beans or configuration classes. - Prefer
@ConfigurationPropertiesfor grouped configuration. - Keep secrets out of property files; use environment sources.