@Profile is a Spring annotation that conditionally creates a bean or configuration class when a specified profile is active. Profiles separate development, testing, and production behavior without changing application code. section 6.3.3 section 6.3
Use @Profile to control when application components are created:
- Apply @Profile("dev") to create a bean only with the dev profile active. section 6.3.3
- Apply @Profile({"dev", "qa"}) to create a bean when either dev or qa is active. section 6.3.3
- Apply @Profile("!prod") to create a bean unless the prod profile is active. section 6.3.3
- Annotate an entire @Configuration class to conditionally create all beans declared in that class. section 6.3.3
Avoid loading development data in production
A CommandLineRunner that loads ingredient data into an embedded database can be limited to development: @Bean followed by @Profile("dev") creates it only for the dev profile. To allow development and testing, use @Profile({"dev", "qa"}); to allow it everywhere except production, use @Profile("!prod"). section 6.3.3
@Bean
@Profile("dev")
public CommandLineRunner dataLoader(IngredientRepository repo,
UserRepository userRepo, PasswordEncoder encoder) {
...
}
Inspect the complete @Bean and @Profile("dev") declaration for a development-only CommandLineRunner. section 6.3.3
@Bean
@Profile("!prod")
public CommandLineRunner dataLoader(IngredientRepository repo,
UserRepository userRepo, PasswordEncoder encoder) {
...
}
Inspect the negated profile form that prevents the bean from being created when production is active. section 6.3.3
