Performance: Conditional bean creation
This affects application startup time and memory usage by controlling which beans are created and loaded into the Spring context.
@Bean @ConditionalOnProperty(name = "feature.serviceA.enabled", havingValue = "true") public ServiceA serviceA() { return new ServiceA(); } @Bean @ConditionalOnProperty(name = "feature.serviceB.enabled", havingValue = "true") public ServiceB serviceB() { return new ServiceB(); }
@Bean
public ServiceA serviceA() {
return new ServiceA();
}
@Bean
public ServiceB serviceB() {
return new ServiceB();
}| Pattern | Beans Created | Startup Time Impact | Memory Usage | Verdict |
|---|---|---|---|---|
| Unconditional bean creation | All beans | High - creates all beans regardless of need | High - all beans consume memory | [X] Bad |
| Conditional bean creation | Only needed beans | Low - skips unnecessary beans | Low - less memory used | [OK] Good |
@ConditionalOnProperty in Spring Boot?@ConditionalOnProperty@ConditionalOnProperty to create a bean only when feature.enabled is true?name for the property key and havingValue for the expected value.name and havingValue correctly, others use invalid parameter names.@Bean
@ConditionalOnProperty(name = "app.feature", havingValue = "enabled")
public Service myService() {
return new Service();
}app.feature=disabled is set in application.properties?app.feature equals "enabled".myService is NOT created -> Option D@Bean
@ConditionalOnProperty(name = "service.enabled", havingValue = "true")
public Service service() {
return new Service();
}service.enabled=true is set in application.properties?application.properties is misspelled or different, condition fails.mode which can be "simple" or "advanced".@ConditionalOnProperty?@ConditionalOnProperty with havingValue set to "simple" or "advanced" on each bean ensures only one bean loads.@ConditionalOnProperty(name = "mode") on both beans without havingValue lacks value check, so both beans may load; Create both beans without conditions and select one at runtime loads both always; Use @ConditionalOnProperty(name = "mode", matchIfMissing = true) on both beans activates both if property missing.Pass the test and this pattern moves unknown