The @Profile annotation in Spring Boot marks a bean or configuration class so it is only registered when a specific named profile, such as dev, test, or prod, is active. It lets a single codebase carry environment-specific wiring without conditional logic scattered through the code.
Key Points: • Applied at the class or method level on @Component, @Configuration, or @Bean definitions. • The active profile is set via spring.profiles.active in application.properties, an environment variable, or a command-line argument. • Multiple profiles can be combined, and profile expressions like !prod support negation. • Commonly used to swap data sources, mail senders, or external service clients per environment. • Beans without a @Profile annotation are always registered regardless of the active profile.
Example: A DataSource bean annotated with @Profile("dev") points to an in-memory H2 database, while a second bean annotated with @Profile("prod") points to the production PostgreSQL instance; Spring only creates the one matching the active profile.
Code Example:
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
@Bean
@Profile("prod")
public DataSource prodDataSource() {
return DataSourceBuilder.create()
.url("jdbc:postgresql://prod-host:5432/app")
.build();
}
}Interview Tip: A concise interview answer is:
"@Profile lets me register beans conditionally based on the active Spring profile, so dev, test, and prod can each get their own configuration without if-else branching. I activate a profile with spring.profiles.active and Spring only creates the beans that match."