Performance: @Profile for environment-specific beans
This concept affects application startup time and memory usage by controlling which beans load based on the environment.
@Component @Profile("dev") public class DevService { /* dev-only logic */ } @Component @Profile("prod") public class ProdService { /* prod-only logic */ }
@Component public class DevService { /* dev-only logic */ } @Component public class ProdService { /* prod-only logic */ }
| Pattern | Beans Loaded | Startup Time | Memory Usage | Verdict |
|---|---|---|---|---|
| No @Profile filtering | All beans | Higher due to extra beans | Higher memory footprint | [X] Bad |
| @Profile filtering active | Only relevant beans | Lower startup time | Lower memory footprint | [OK] Good |
@Profile annotation in Spring Boot?@Profile@Profile annotation is used to mark beans that should only be created when a specific environment profile is active.@Profile on a Spring bean class for the "dev" environment?@Profile annotation requires a string value in quotes, e.g., @Profile("dev").@Profile("dev")
@Component
public class DevBean {
public String getMessage() { return "Development Bean"; }
}
@Profile("prod")
@Component
public class ProdBean {
public String getMessage() { return "Production Bean"; }
}
@Component
public class BeanUser {
private final Object bean;
public BeanUser(@Autowired(required = false) Object bean) { this.bean = bean; }
public String show() { return bean == null ? "No Bean" : ((ProdBean)bean).getMessage(); }
}ProdBean is created. DevBean is not created.Object bean with @Autowired(required = false). Spring injects the available ProdBean instance as it matches.show(), bean is cast to ProdBean, which succeeds, returning "Production Bean".@Profile("test") and @Profile("prod") respectively. When running the app with no active profile set, you get a NoSuchBeanDefinitionException. What is the most likely cause?@Profile annotation usage correctly achieves this?@Profile({"dev", "test"}) means the bean is active if either "dev" OR "test" profile is active.Pass the test and this pattern moves unknown