@Value & Dynamic Beans
Injecting config values with @Value, SpEL, @ConfigurationProperties, dynamic bean registration
- Inject application.properties values with @Value
- Use SpEL for conditional and computed injections
- Bind hierarchical config to a @ConfigurationProperties POJO
Spring Boot Series | Concept and Coding
Table of Contents
- Prerequisites — What You Need to Know First
- The Problem — Unsatisfied Dependency
- Quick Fix Recap — @Qualifier
- Why @Qualifier Breaks Dependency Inversion
- Solution 1 — Dynamic Selection via @Qualifier at Runtime (Industry Standard)
- Solution 2 — Dynamic Bean Initialization via @Value and @Bean
- @Value Annotation — Deep Dive
- application.properties — The Configuration File
- Complete Execution Flow
- Solution 1 vs Solution 2 — Comparison
- Key Diagrams
- Interview Notes
- Common Mistakes
- Summary Cheat Sheet
1. Prerequisites What You Need to Know First
Before understanding dynamic bean initialization, you need to be comfortable with these concepts. They are briefly summarized here so the notes remain self-contained.
Dependency Injection (DI)
Spring Boot manages objects (called beans) and automatically provides them wherever they are needed — this is called Dependency Injection.
1@Component2public class UserService {3
4 @Autowired5 private OrderService orderService; // Spring injects this — you don't create it manually6}@Component
Marks a class so Spring automatically detects it during component scanning and registers it as a bean in the Spring ApplicationContext.
@Autowired
Tells Spring to inject a matching bean into this field, constructor, or setter.
Dependency Inversion Principle (DIP)
A software design principle from SOLID that states:
High-level modules should not depend on low-level modules. Both should depend on abstractions (interfaces).
In practice this means: instead of depending on a concrete class (OnlineOrder), depend on an interface (Order). This allows the concrete implementation to be swapped at runtime without changing the high-level code.
@Bean and @Configuration
@Bean is used inside a @Configuration class to manually declare a bean — telling Spring exactly how to create it. This is an alternative to @Component.
1@Configuration2public class AppConfig {3
4 @Bean5 public Order createOrderBean() {6 return new OnlineOrder(); // You control what Spring creates7 }8}2. The Problem Unsatisfied Dependency
Setup
Consider this design:
1// The abstraction (interface)2public interface Order {3 void createOrder();4}5
6// Implementation 17@Component8public class OnlineOrder implements Order {9
10 @Override11 public void createOrder() {12 System.out.println("Created Online Order");13 }14}15
16// Implementation 217@Component18public class OfflineOrder implements Order {19
20 @Override21 public void createOrder() {22 System.out.println("Created Offline Order");23 }24}1// The controller that depends on Order2@RestController3public class UserController {4
5 @Autowired6 private Order order; // Which one? OnlineOrder or OfflineOrder?7
8 @GetMapping("/createOrder")9 public String createOrder() {10 order.createOrder();11 return "Order created";12 }13}What Happens at Startup
1Application Start2 │3 ▼4Spring scans for components5 │6 ▼7Spring finds UserController (singleton — created eagerly at startup)8 │9 ▼10Spring tries to resolve dependency: Order11 │12 ▼13Spring finds TWO beans implementing Order:14 - OnlineOrder (via @Component)15 - OfflineOrder (via @Component)16 │17 ▼18Spring doesn't assume which one to pick19 │20 ▼21❌ APPLICATION FAILS TO STARTError:
1UnsatisfiedDependencyException: Error creating bean with name 'userController':2Unsatisfied dependency expressed through field 'order';3expected single matching bean but found 2: onlineOrder, offlineOrderWhy Spring Doesn't Just Pick One
Spring follows the principle of least surprise. Silently picking an implementation could cause wrong business behaviour. Spring prefers to fail loudly and let you decide explicitly.
3. Quick Fix Recap @Qualifier
@Qualifier was introduced to resolve ambiguity — you explicitly name the bean you want injected.
How It Works
1// Tag OnlineOrder with a qualifier name2@Component3@Qualifier("onlineOrderObject")4public class OnlineOrder implements Order {5 @Override6 public void createOrder() {7 System.out.println("Created Online Order");8 }9}10
11// Tag OfflineOrder with a qualifier name12@Component13@Qualifier("offlineOrderObject")14public class OfflineOrder implements Order {15 @Override16 public void createOrder() {17 System.out.println("Created Offline Order");18 }19}1@RestController2public class UserController {3
4 @Autowired5 @Qualifier("onlineOrderObject") // ← Tell Spring exactly which bean to inject6 private Order order;7
8 @GetMapping("/createOrder")9 public String createOrder() {10 order.createOrder();11 return "Order created";12 }13}Result: Spring always injects OnlineOrder. The ambiguity is resolved.
4. Why @Qualifier Breaks Dependency Inversion
The Problem with Hard-Coding the Qualifier
1@Autowired2@Qualifier("onlineOrderObject") // ← This is HARD-CODED3private Order order;By hard-coding "onlineOrderObject", you have permanently decided that UserController will always use OnlineOrder. This violates the Dependency Inversion Principle because:
UserController(high-level) is now rigidly tied toOnlineOrder(low-level implementation)- You cannot switch to
OfflineOrderwithout modifyingUserController - The interface
Orderprovides no real abstraction benefit — the implementation is fixed
What DIP Promises vs What We Have
| Expectation (DIP) | Reality with Hard-Coded @Qualifier |
|---|---|
| Implementation can be swapped dynamically | Implementation is fixed at compile time |
| High-level module doesn't know about low-level | Controller explicitly references "onlineOrderObject" |
| Easy to extend with new implementations | Adding a new implementation requires code changes in controller |
The Goal
We need a way to decide at runtime (or via configuration) which implementation to use — without hard-coding the choice in the controller. Two solutions achieve this:
- Solution 1 — Select between pre-injected beans based on runtime input (client request)
- Solution 2 — Configure which bean Spring creates using
@Valueandapplication.properties
5. Solution 1 Dynamic Selection via @Qualifier at Runtime (Industry Standard)
Overview
Instead of injecting one bean and hard-coding which one, inject both beans into the controller and choose between them at runtime based on input (e.g., a request parameter from the client).
Full Code
1// Interface — unchanged2public interface Order {3 void createOrder();4}5
6// OnlineOrder — with qualifier7@Component8@Qualifier("onlineOrderObject")9public class OnlineOrder implements Order {10 @Override11 public void createOrder() {12 System.out.println("Created Online Order");13 }14}15
16// OfflineOrder — with qualifier17@Component18@Qualifier("offlineOrderObject")19public class OfflineOrder implements Order {20 @Override21 public void createOrder() {22 System.out.println("Created Offline Order");23 }24}1@RestController2public class UserController {3
4 // Inject BOTH beans — each identified by its qualifier5 @Autowired6 @Qualifier("onlineOrderObject")7 private Order onlineOrder; // OnlineOrder bean injected here8
9 @Autowired10 @Qualifier("offlineOrderObject")11 private Order offlineOrder; // OfflineOrder bean injected here12
13 @GetMapping("/createOrder")14 public String createOrder(@RequestParam boolean isOnlineOrder) {15 // Choose dynamically based on client input16 if (isOnlineOrder) {17 onlineOrder.createOrder();18 return "Online order created";19 } else {20 offlineOrder.createOrder();21 return "Offline order created";22 }23 }24}How It Works
1Application Startup (Singleton beans created):2 OnlineOrder bean ──────────────────► injected into "onlineOrder" field3 OfflineOrder bean ──────────────────► injected into "offlineOrder" field4
5Runtime (Client sends request):6 GET /createOrder?isOnlineOrder=true → onlineOrder.createOrder() → "Created Online Order"7 GET /createOrder?isOnlineOrder=false → offlineOrder.createOrder() → "Created Offline Order"Why This Doesn't Fully Break DIP
- Both beans are singletons — created once at startup
- The controller holds references to both
- The decision of which to use is made at runtime based on external input
- Adding a new order type (e.g.,
InternationalOrder) only requires adding a new bean and adding a new branch in the selection logic — the interface is unchanged
Testing
1GET /createOrder?isOnlineOrder=true2→ Output: Created Online Order3
4GET /createOrder?isOnlineOrder=false5→ Output: Created Offline Order6. Solution 2 Dynamic Bean Initialization via @Value and @Bean
Overview
Instead of injecting both beans and choosing between them, configure Spring to create only one bean — and control which one through application.properties. Changing a property value switches the implementation without touching Java code.
Key Difference from Solution 1
| Solution 1 | Solution 2 | |
|---|---|---|
| Who decides? | Client (runtime request param) | Configuration file (deploy-time property) |
| Both beans created? | Yes (both singletons exist) | No (only one bean created) |
| Change requires? | Different request param | Change in application.properties |
| Use case | User-driven selection per request | Environment/deployment-driven selection |
The Classes No @Component
1// Interface — unchanged2public interface Order {3 void createOrder();4}5
6// OnlineOrder — NO @Component (Spring won't auto-create this)7public class OnlineOrder implements Order {8 @Override9 public void createOrder() {10 System.out.println("Created Online Order");11 }12}13
14// OfflineOrder — NO @Component (Spring won't auto-create this)15public class OfflineOrder implements Order {16 @Override17 public void createOrder() {18 System.out.println("Created Offline Order");19 }20}@Component on either implementation class. Spring will not auto-create beans for them. We are taking full manual control via @Configuration and @Bean.The Configuration Class
1@Configuration2public class OrderConfig {3
4 @Value("${is.online.order}") // Read value from application.properties5 private boolean isOnlineOrder;6
7 @Bean8 public Order createOrderBean() {9 if (isOnlineOrder) {10 return new OnlineOrder(); // Spring manages this OnlineOrder as the "order" bean11 } else {12 return new OfflineOrder(); // Spring manages this OfflineOrder as the "order" bean13 }14 }15}The Configuration File application.properties
1# application.properties2is.online.order=falseThe Controller Clean, No Qualifier Logic
1@RestController2public class UserController {3
4 @Autowired5 private Order order; // Spring injects whichever bean was created by OrderConfig6
7 @GetMapping("/createOrder")8 public String createOrder() {9 order.createOrder();10 return "Order created";11 }12}What Happens at Startup
1Application Starts2 │3 ▼4Spring reads application.properties5 is.online.order = false6 │7 ▼8@Value injects false into OrderConfig.isOnlineOrder9 │10 ▼11Spring calls createOrderBean()12 isOnlineOrder = false → returns new OfflineOrder()13 │14 ▼15Spring registers OfflineOrder as the "order" bean16 │17 ▼18UserController is initialized (singleton)19 @Autowired Order → OfflineOrder is injected20 │21 ▼22GET /createOrder → order.createOrder() → "Created Offline Order"Switching Implementations
To switch to OnlineOrder, change one line in application.properties:
1# Change this:2is.online.order=false3
4# To this:5is.online.order=trueRestart the application. Now OnlineOrder is created and injected. No Java code changed.
7. @Value Annotation Deep Dive
Overview
@Value is a Spring annotation used to inject values from external sources into Spring-managed beans. It is one of the most versatile configuration tools in Spring Boot.
Definition
@Valueinjects a value into a Spring bean field, constructor parameter, or method parameter. The value can come from property files, environment variables, system properties, or be a literal provided inline.
Syntax
1@Value("${property.key}") // From application.properties / environment variable2@Value("${property.key:default}") // With a default value if key is not found3@Value("literal value") // Inline literal — direct value4@Value("#{expression}") // Spring Expression Language (SpEL)The Placeholder Syntax
1@Value("${is.online.order}")2 │─────────────│3 This is the KEY in application.propertiesThe ${} syntax is a property placeholder. Spring resolves it by:
- Looking in
application.properties - Looking in environment variables
- Looking in system properties
- If still not found and no default provided — throws
IllegalArgumentException
Sources @Value Can Inject From
1. application.properties
1# application.properties2is.online.order=true3app.name=MyApplication4server.timeout=301@Value("${is.online.order}")2private boolean isOnlineOrder; // true3
4@Value("${app.name}")5private String appName; // "MyApplication"6
7@Value("${server.timeout}")8private int timeout; // 302. Environment Variables
If your OS or Docker container has an environment variable set:
1export IS_ONLINE_ORDER=trueSpring Boot can pick this up (with some naming convention mapping). This is common in cloud/containerized deployments.
3. Inline Literals
You can directly embed a value without a property file:
1@Value("true")2private boolean isOnlineOrder; // Always true — hardcoded3
4@Value("Shreyansh")5private String name; // Always "Shreyansh"6
7@Value("42")8private int port; // Always 424. Default Values
If the property might not always be defined, provide a fallback:
1@Value("${is.online.order:true}") // If key not found, use "true" as default2private boolean isOnlineOrder;The syntax is ${key:default} — a colon separates the key from the default.
Type Conversion
Like @RequestParam, Spring automatically converts the property string to the declared Java type:
1@Value("${server.port}")2private int port; // "8080" (String) → 8080 (int)3
4@Value("${feature.enabled}")5private boolean enabled; // "true" (String) → true (boolean)6
7@Value("${max.retries}")8private double maxRetries; // "3.5" (String) → 3.5 (double)@Value in Different Injection Points
1// Field injection2@Component3public class MyService {4 @Value("${app.name}")5 private String appName;6}7
8// Constructor injection (preferred for testability)9@Component10public class MyService {11 private final String appName;12
13 public MyService(@Value("${app.name}") String appName) {14 this.appName = appName;15 }16}17
18// Method parameter injection (in @Bean methods)19@Configuration20public class AppConfig {21
22 @Bean23 public Order createOrderBean(@Value("${is.online.order}") boolean isOnlineOrder) {24 return isOnlineOrder ? new OnlineOrder() : new OfflineOrder();25 }26}8. application.properties The Configuration File
What It Is
application.properties is Spring Boot's primary configuration file. It lives in:
1src/2└── main/3 └── resources/4 └── application.properties ← hereFormat
Simple key=value pairs, one per line:
1# Server configuration2server.port=80803
4# Database5spring.datasource.url=jdbc:mysql://localhost:3306/mydb6spring.datasource.username=root7spring.datasource.password=secret8
9# Custom application properties10is.online.order=true11app.name=ConceptAndCoding12max.order.limit=100How Spring Reads It
At application startup, Spring Boot automatically:
- Finds
application.propertiesinsrc/main/resources/ - Loads all key-value pairs into the
Environment - Resolves
@Value("${key}")placeholders by looking up the key in theEnvironment
Naming Convention
Property keys follow a dot-separated, lowercase convention:
1# Good — follows convention2is.online.order=true3app.max.connections=104feature.dark.mode.enabled=false5
6# Works but not idiomatic7IsOnlineOrder=true ← avoid camelCase8IS_ONLINE_ORDER=true ← environment variable styleMultiple Environments with Profiles
Spring Boot supports environment-specific property files:
1application.properties ← default (always loaded)2application-dev.properties ← loaded when profile "dev" is active3application-prod.properties ← loaded when profile "prod" is active1# application-dev.properties2is.online.order=true3
4# application-prod.properties5is.online.order=falseActivate a profile:
1# application.properties2spring.profiles.active=dev9. Complete Execution Flow
Solution 2 Step-by-Step Bean Creation
Changing the Configuration
1Step 1: Change application.properties2 is.online.order=false → is.online.order=true3
4Step 2: Restart the application5
6Step 3: Spring re-reads properties7 isOnlineOrder = true8 createOrderBean() → returns new OnlineOrder()9
10Step 4: OnlineOrder is now the "order" bean11 UserController gets OnlineOrder injected12
13Step 5: API call14 GET /createOrder → "Created Online Order"10. Solution 1 vs Solution 2 Comparison
Full Comparison Table
| Aspect | Solution 1 (@Qualifier at Runtime) | Solution 2 (@Value + @Bean) |
|---|---|---|
| Decision maker | Client (per-request parameter) | Configuration file (at startup) |
| When decided | At runtime, each request | At startup (once per application lifecycle) |
| Both beans created? | Yes — both OnlineOrder and OfflineOrder beans exist | No — only one bean is created |
| Flexibility | Per-request — different users can get different order types | Per-deployment — all users get same order type |
| Code complexity | Slightly more (two @Autowired fields + if/else in method) | Slightly more initial setup (@Configuration class) |
| Change requires | Different client input | Property file change + restart |
| Use case | Feature toggles per user, A/B testing, user-specific behavior | Environment-based config (dev/staging/prod differences) |
| Industry usage | Very common for user-driven routing | Very common for environment configuration |
When to Use Which
1Is the choice made per-request based on user input?2 YES → Solution 1 (@Qualifier with both beans injected, runtime if/else)3
4Is the choice made per-deployment based on environment?5 YES → Solution 2 (@Value reading from application.properties)Real-World Examples
Solution 1 (Runtime Selection):
- Payment gateway: PayPal vs Stripe — user chooses at checkout
- Notification: Email vs SMS — user preference setting
- Order type: Online vs In-store — user selects at order creation
Solution 2 (Config-Based Selection):
- Development environment uses a mock payment gateway; production uses real one
- Local environment uses H2 in-memory DB; production uses MySQL
- Feature flag: new recommendation algorithm enabled in production only
11. Key Diagrams
The Unsatisfied Dependency Problem
Solution 1 Both Beans, Runtime Choice
Solution 2 @Value + @Bean, Config-Based Choice
@Value Sources Mind Map
12. Interview Notes
Common Interview Questions and Answers
Q1: What is the Unsatisfied Dependency problem in Spring?
Answer: When Spring finds two or more beans of the same type and tries to autowire a field of that type, it cannot determine which bean to inject. Since Spring doesn't assume, it throws UnsatisfiedDependencyException and the application fails to start.
Q2: How does @Qualifier resolve the Unsatisfied Dependency problem?
Answer: @Qualifier lets you assign a name to a bean and then reference that specific name at the injection point. Spring injects the bean whose qualifier name matches, resolving the ambiguity.
Q3: Why does @Qualifier break Dependency Inversion?
Answer: When you hard-code a qualifier name at the injection point (e.g., @Qualifier("onlineOrderObject")), you permanently bind the high-level module (controller) to a specific low-level implementation. The choice of implementation is made at compile time, not at runtime, so you lose the flexibility to swap implementations without modifying the controller.
Q4: What is @Value used for in Spring Boot?
Answer: @Value injects values into Spring beans from external sources — primarily application.properties, environment variables, or as inline literals. It allows configuration values to be externalized from code, supporting different behavior across environments without code changes.
Q5: What is the difference between `@Value("${key}")` and `@Value("literal")`?
Answer:
@Value("${key}")is a property placeholder — Spring looks up the key inapplication.properties(or environment) and injects the value found there. The value is external and configurable.@Value("literal")is an inline literal — the string"literal"is directly assigned. It doesn't look anything up. Useful for testing, but removes configurability.
Q6: What happens if a @Value key is not found in application.properties?
Answer: Spring throws IllegalArgumentException at startup: Could not resolve placeholder 'key' in value "${key}". To avoid this, provide a default: @Value("${key:defaultValue}").
Q7: What is the difference between Solution 1 and Solution 2 for dynamic bean selection?
Answer:
- Solution 1 injects multiple beans and selects between them at runtime per request using if/else logic — suitable when user input determines the implementation.
- Solution 2 uses
@Valueto read a property at startup and creates only one bean based on that property — suitable when the environment or deployment configuration determines the implementation.
Q8: Why is @Component removed in Solution 2?
Answer: In Solution 2, we use a @Configuration class with @Bean to manually control bean creation. If @Component were still present on OnlineOrder and OfflineOrder, Spring would auto-create beans for both AND the @Bean method would create another — leading back to the ambiguity problem. Removing @Component means Spring only creates beans through the explicit @Bean method.
Q9: Can @Value inject values into non-Spring-managed classes?
Answer: No. @Value only works in classes managed by the Spring container (i.e., classes annotated with @Component, @Service, @Repository, @Controller, @Configuration, or registered via @Bean). Plain Java objects (POJOs) not managed by Spring cannot use @Value.
Q10: What is the difference between @Value and @ConfigurationProperties?
@Value | @ConfigurationProperties | |
|---|---|---|
| Binds | Single property | Group of related properties |
| Syntax | @Value("${key}") per field | One annotation on the class |
| Type safety | Manual per field | Fully type-safe |
| Best for | A few individual values | Structured configuration groups |
13. Common Mistakes
Mistake 1 Using @Component Alongside @Bean for the Same Class
1// ❌ Wrong — @Component creates a bean AND @Bean creates another → ambiguity2@Component3public class OnlineOrder implements Order { ... }4
5@Configuration6public class OrderConfig {7 @Bean8 public Order createOrderBean() {9 return new OnlineOrder(); // Now TWO OnlineOrder beans exist10 }11}1// ✅ Correct — choose one approach2// Either use @Component (auto-managed):3@Component4public class OnlineOrder implements Order { ... }5
6// OR use @Bean (manually managed) — remove @Component:7public class OnlineOrder implements Order { ... }8
9@Configuration10public class OrderConfig {11 @Bean12 public Order createOrderBean() { ... }13}Mistake 2 @Value on a Non-Spring-Managed Class
1// ❌ Wrong — plain POJO, not managed by Spring2public class OrderConfig {3
4 @Value("${is.online.order}") // Spring never sees this — value stays null/false5 private boolean isOnlineOrder;6}1// ✅ Correct — must be a Spring-managed bean2@Configuration // ← Makes this a Spring bean3public class OrderConfig {4
5 @Value("${is.online.order}") // Now Spring injects the value6 private boolean isOnlineOrder;7}Mistake 3 Mismatched Property Key
1# application.properties2is.online.order=true1// ❌ Wrong — key doesn't match2@Value("${isOnlineOrder}") // Looks for "isOnlineOrder" — not found!3private boolean isOnlineOrder; // Throws IllegalArgumentException at startup1// ✅ Correct — key must match exactly2@Value("${is.online.order}") // Matches "is.online.order" in properties file3private boolean isOnlineOrder;Mistake 4 No Default Value for Optional Properties
1// ❌ Risky — if "is.online.order" is missing from properties, app crashes2@Value("${is.online.order}")3private boolean isOnlineOrder;1// ✅ Safe — provide a default value2@Value("${is.online.order:true}") // Defaults to true if key is absent3private boolean isOnlineOrder;Mistake 5 Using @Value in a Static Field
1// ❌ Wrong — @Value doesn't work with static fields2@Component3public class Config {4
5 @Value("${is.online.order}")6 private static boolean isOnlineOrder; // Always false (default) — @Value ignored7}1// ✅ Correct — use instance fields only2@Component3public class Config {4
5 @Value("${is.online.order}")6 private boolean isOnlineOrder; // Works correctly7}Mistake 6 Forgetting to Restart After Property Change (Solution 2)
In Solution 2, @Value is read at startup only. If you change application.properties while the app is running, the change has no effect until you restart.
14. Summary Cheat Sheet
The Problem and Solutions
1Problem: Two beans implement the same interface → Spring can't choose → UnsatisfiedDependencyException2
3Solution 1: Inject both beans, choose at runtime4 - Both beans exist (singletons)5 - if/else selects based on request input6 - Best for: per-request, user-driven selection7
8Solution 2: Create one bean conditionally via @Value9 - Only one bean exists10 - Property file controls which one11 - Best for: environment/deployment-level configuration@Value Quick Reference
| Syntax | Source | Example |
|---|---|---|
@Value("${key}") | application.properties | @Value("${is.online.order}") |
@Value("${key:default}") | Properties with fallback | @Value("${timeout:30}") |
@Value("literal") | Inline literal | @Value("true") |
@Value("#{expression}") | Spring Expression Language | @Value("#{2 * 3}") |
Annotation Roles in This Topic
| Annotation | Role |
|---|---|
@Qualifier | Names a bean and specifies which bean to inject |
@Value | Injects external configuration values into a bean field |
@Bean | Manually declares a bean in a @Configuration class |
@Configuration | Marks a class as a source of bean definitions |
@Component | Auto-registers a class as a Spring bean |
@Autowired | Tells Spring to inject a dependency |
Decision Guide
1Multiple implementations of an interface?2 │3 ├── User chooses per request?4 │ → Solution 1: Inject all with @Qualifier, if/else at runtime5 │6 └── Environment determines which one?7 → Solution 2: @Configuration + @Bean + @Value from application.propertiesapplication.properties Location
1src/2└── main/3 └── resources/4 └── application.properties ← Spring Boot reads this automaticallyStudy Guide — Dynamic Bean Initialization | Spring Boot Series | Concept and Coding
Mastery check
How well can you recall this?
Finished this lesson?