Discover how to make your Spring Boot app smartly create only the beans it really needs!
Why Conditional bean creation in Spring Boot? - Purpose & Use Cases
Imagine building a Spring Boot app where you must manually check environment settings and decide which service objects to create.
You write code everywhere to create or skip beans based on conditions like profiles or properties.
This manual approach is messy and error-prone.
You risk creating duplicate beans or missing needed ones.
It makes your code hard to read and maintain.
Conditional bean creation lets Spring automatically create beans only when certain conditions are met.
You declare conditions with simple annotations, and Spring handles the rest.
if (env.equals("prod")) { return new ProdService(); } else { return new DevService(); }
@Bean @ConditionalOnProperty(name = "app.env", havingValue = "prod") public ProdService prodService() { return new ProdService(); }
This makes your app flexible and clean, adapting bean creation automatically to different environments or settings.
For example, you can create a real payment gateway bean only in production, and a mock one in development, without changing code.
Manual bean creation based on conditions is complex and fragile.
Conditional bean creation uses annotations to automate this process.
This leads to cleaner, safer, and more maintainable Spring Boot apps.
Practice
@ConditionalOnProperty in Spring Boot?Solution
Step 1: Understand the role of
This annotation checks if a property is set in the application configuration.@ConditionalOnPropertyStep 2: Effect on bean creation
If the property matches the condition, Spring Boot creates the bean; otherwise, it skips it.Final Answer:
To create a bean only if a specific property is set in the configuration -> Option CQuick Check:
Conditional bean creation = property check [OK]
- Thinking it always creates beans
- Confusing it with disabling all beans
- Assuming it only works in tests
@ConditionalOnProperty to create a bean only when feature.enabled is true?Solution
Step 1: Recall correct annotation parameters
The correct parameters arenamefor the property key andhavingValuefor the expected value.Step 2: Match with options
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true") usesnameandhavingValuecorrectly, others use invalid parameter names.Final Answer:
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true") -> Option BQuick Check:
Correct params = name + havingValue [OK]
- Using wrong parameter names like 'property' or 'key'
- Confusing 'havingValue' with 'value'
- Using boolean true without quotes
@Bean
@ConditionalOnProperty(name = "app.feature", havingValue = "enabled")
public Service myService() {
return new Service();
}What happens if the property
app.feature=disabled is set in application.properties?Solution
Step 1: Understand the condition
The bean is created only ifapp.featureequals "enabled".Step 2: Check the property value
The property is set to "disabled", which does not match "enabled".Final Answer:
The beanmyServiceis NOT created -> Option DQuick Check:
Property mismatch = no bean creation [OK]
- Assuming bean creates regardless of property value
- Thinking app fails to start on mismatch
- Believing bean is created but inactive
@Bean
@ConditionalOnProperty(name = "service.enabled", havingValue = "true")
public Service service() {
return new Service();
}Why does the bean never get created even when
service.enabled=true is set in application.properties?Solution
Step 1: Verify property key spelling
If the property key inapplication.propertiesis misspelled or different, condition fails.Step 2: Check other options
HavingValue compares strings, so boolean type mismatch is not an issue; @Component is not needed on @Bean methods; static is not required.Final Answer:
The property key name is incorrect or misspelled -> Option AQuick Check:
Property key must match exactly [OK]
- Assuming boolean type mismatch causes failure
- Thinking @Component is needed on @Bean methods
- Believing bean methods must be static
mode which can be "simple" or "advanced".Which is the best way to define these beans using
@ConditionalOnProperty?Solution
Step 1: Understand the requirement
Only one bean should be active depending on the property value "simple" or "advanced".Step 2: Apply conditional annotations
Using@ConditionalOnPropertywithhavingValueset to "simple" or "advanced" on each bean ensures only one bean loads.Step 3: Evaluate other options
Use@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.Final Answer:
Use @ConditionalOnProperty(name = "mode", havingValue = "simple") on the simple bean and @ConditionalOnProperty(name = "mode", havingValue = "advanced") on the advanced bean -> Option AQuick Check:
Use havingValue to select one bean by property [OK]
- Not specifying havingValue causing both beans to load
- Trying to select bean at runtime instead of conditionally
- Using matchIfMissing on both beans causing conflicts
Ready to prove it?
Pass the test and this pattern moves unknown
