How to Use @Profile Annotation in Spring for Environment-Specific Beans
Use the
@Profile annotation on Spring components or configuration classes to specify which environment or profile they belong to. Beans annotated with @Profile are only created when their profile is active, allowing environment-specific configurations.Syntax
The @Profile annotation is placed on a Spring component or configuration class to specify one or more profiles under which the bean should be active.
@Profile("profileName"): Activates the bean only ifprofileNameis active.- You can specify multiple profiles with
@Profile({"dev", "test"})to activate the bean if any listed profile is active.
java
@Profile("dev") @Component public class DevDatabaseConfig { // Bean definitions for dev environment }
Example
This example shows two configuration classes with @Profile annotations for dev and prod environments. Spring will load only the beans matching the active profile.
java
import org.springframework.context.annotation.*; import org.springframework.stereotype.Component; @Profile("dev") @Component class DevService { public String getMessage() { return "Running in Development"; } } @Profile("prod") @Component class ProdService { public String getMessage() { return "Running in Production"; } } @Configuration @ComponentScan public class AppConfig { } public class MainApp { public static void main(String[] args) { System.setProperty("spring.profiles.active", "dev"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); DevService service = context.getBean(DevService.class); System.out.println(service.getMessage()); context.close(); } }
Output
Running in Development
Common Pitfalls
- Not setting the active profile properly, so no beans with
@Profileare loaded. - Using
@Profileon beans without matching active profiles causesNoSuchBeanDefinitionException. - For multiple profiles, remember
@Profile({"dev", "test"})means bean loads if any profile matches, not all.
java
/* Wrong: No active profile set, bean won't load */ @Component @Profile("dev") public class DevOnlyBean {} /* Right: Set active profile to 'dev' to load bean */ System.setProperty("spring.profiles.active", "dev");
Quick Reference
| Usage | Description |
|---|---|
| @Profile("dev") | Bean active only when 'dev' profile is active |
| @Profile({"dev", "test"}) | Bean active if 'dev' or 'test' profile is active |
| spring.profiles.active | System property or config to set active profile |
| No @Profile | Bean always active regardless of profile |
Key Takeaways
Use @Profile to load beans only in specific environments like dev or prod.
Set the active profile using 'spring.profiles.active' to control which beans load.
Multiple profiles in @Profile mean the bean loads if any listed profile is active.
Without matching active profiles, beans annotated with @Profile won't be created.
Use @Profile on configuration classes or components to organize environment-specific code.