📌 What it is
@Value
is a Spring Framework annotation used for dependency injection of values into fields, method parameters, or constructor arguments.
It allows you to read values from:
-
application.properties
orapplication.yml
- System environment variables
- Command-line arguments
- SpEL (Spring Expression Language) expressions
💡 Why we use it
-
Externalize Configuration
Instead of hardcoding values (like URLs, usernames, etc.) in code, you can keep them inapplication.properties
or environment variables.
name=Gaurav
Then inject it:
@Value("${name}")
private String name;
-
Easier Maintenance
When configuration changes (like database URL, API key, etc.), you can just update the.properties
file — no code change required. -
Environment Flexibility
Helps when deploying the same app in multiple environments — dev, test, prod — each with different configurations.
🕐 When to use it
Use @Value
when:
- You need simple static configuration values (e.g., strings, numbers, booleans).
- You want to inject a single property directly from
application.properties
. - You need to evaluate small expressions (e.g.,
${timeout:30}
means use 30 iftimeout
is missing).
Example scenarios:
- Injecting API base URLs
- Setting retry counts, timeouts, feature toggles
- Reading environment-specific constants
⚙️ How it works (internally)
- When Spring Boot starts, it loads all configuration files (
application.properties
,application.yml
, etc.). - It creates a Spring Environment object that holds key–value pairs.
- When Spring encounters
@Value("${name}")
, it:
- Looks up
"name"
in the Environment. - Retrieves the value.
- Injects it into the constructor argument (or field).
- The bean is then created with that injected value.
🧩 Example in full context
application.properties
app.title=Backend
Java class
@Component
public class ConfigTestClass {
private final String appTitle;
public ConfigTestClass(@Value("${app.title}") String appTitle) {
this.appTitle = appTitle;
}
@PostConstruct
public void printValue() {
System.out.println("App Title: " + appTitle);
}
}
🟢 Output on startup:
App Title: Backend
🧠 Extra: Alternatives to @Value
For injecting multiple properties or grouping them:
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String title;
private String version;
}
Then in application.properties
:
app.title= Backend
app.version=1.0
✅ Best practice for larger configurations.
📚 Summary
Aspect | Description |
---|---|
Annotation | @Value("${propertyName}") |
Purpose | Injects values from config files or environment |
Used in | Fields, constructors, or methods |
When to use | For simple, single property injection |
How it works | Spring resolves ${} placeholders from Environment and injects them |
Alternative |
@ConfigurationProperties for bulk config mapping |