Sub topic 3
Choosing Beans and Configuration by Profile
Assume you know basic Java, Spring beans, dependency injection, and YAML or .properties syntax. This chapter shows how to select beans and configuration for different environments.
Choosing beans per profile with `@Profile`
A Spring profile is a named set of configuration choices. @Profile tells Spring to create a bean only when a profile is active.
@Configuration
class NotifierConfig {
@Bean
@Profile("!prod")
Notifier loggingNotifier() {
return message -> System.out.println("[dev] " + message);
}
@Bean
@Profile("prod")
Notifier emailNotifier(MailProperties mail) {
return message -> System.out.println("Sending via "
+ mail.host() + ": " + message);
}
}With prod active, only emailNotifier is created. Without prod, loggingNotifier is created. Ensure that exactly one bean matches, or use a qualifier when multiple beans are intentional.
Profile groups and includes
A profile group activates several profiles with one name:
spring:
profiles:
group:
prod:
- proddb
- prodmqActivating prod also activates proddb and prodmq. Groups make deployment commands shorter and keep related choices together.
Importing extra configuration
Use spring.config.import to load another configuration source:
spring:
config:
import: "optional:file:./local-overrides.yaml"optional: allows startup to continue when the file does not exist. This is useful for local overrides. Do not use it to hide a required production configuration file.
Keeping secrets out of configuration files
Keep passwords, tokens, and private keys outside version control. Supply them through environment variables, a secret manager, or a deployment platform.
Testing with profiles and overrides
Use @ActiveProfiles to select a profile and @SpringBootTest(properties = ...) for test-only values. Test properties override values loaded from normal application files.
@SpringBootTest(properties = "app.mail.port=2525")
@ActiveProfiles("prod")
class MailPropertiesTest {
@Autowired MailProperties mail;
@Test
void usesTestPort() {
assertThat(mail.port()).isEqualTo(2525);
}
}Metadata and effective configuration
@ConfigurationProperties classes can provide IDE completion and documentation when configuration metadata is generated. Prefer them for related settings.
To debug unexpected values, inspect the active profiles and effective environment through Spring Boot’s Actuator environment and configuration-properties endpoints. Protect these endpoints and redact sensitive values.
Exercise
Which command activates the prod profile while allowing an environment variable to override the mail host?
Show answer
SPRING_PROFILES_ACTIVE=prod APP_MAIL_HOST=smtp.internal.example java -jar app.jar