The @Value annotation helps you get values from configuration files into your code easily. It saves you from hardcoding values.
@Value for property injection in Spring Boot
@Value("${property.key}")
private DataType variableName;The ${property.key} is the key name in your properties file.
Make sure the property exists in your application.properties or application.yml.
app.name from your properties into appName.@Value("${app.name}")
private String appName;server.port or uses 8080 as a default if the property is missing.@Value("${server.port:8080}") private int serverPort;
false if not set.@Value("${feature.enabled:false}")
private boolean featureEnabled;This Spring Boot app reads app.greeting and app.version from properties. It prints them when the app starts. If app.version is missing, it uses "1.0" as default.
package com.example.demo; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @Component class PropertyPrinter implements CommandLineRunner { @Value("${app.greeting}") private String greeting; @Value("${app.version:1.0}") private String version; @Override public void run(String... args) { System.out.println(greeting + " - Version: " + version); } }
If the property is missing and no default is given, the app will fail to start.
You can use @Value on fields, constructor parameters, or setter methods.
For complex configurations, consider using @ConfigurationProperties instead.
@Value injects config values into your Spring beans.
You can provide default values using a colon : inside the expression.
It helps keep your code flexible and easy to configure.
Practice
@Value annotation in Spring Boot?Solution
Step 1: Understand the role of
@Value@Valueis used to inject configuration values like those fromapplication.propertiesinto Spring beans.Step 2: Compare with other options
Defining beans, handling HTTP requests, and database connections are done by other annotations or classes, not@Value.Final Answer:
To inject values from configuration files into Spring beans -> Option DQuick Check:
@Value injects config values = A [OK]
- Confusing @Value with @Bean or @Autowired
- Thinking @Value handles HTTP or DB tasks
- Ignoring that @Value reads from properties
app.name using @Value?Solution
Step 1: Recall correct syntax for property injection
The property key must be inside ${} and the whole expression inside quotes:@Value("${property.key}").Step 2: Check each option
@Value("${app.name}") private String appName;matches the correct syntax. The other options miss either the quotes around the expression, the ${} delimiters, or use quotes around just the property name.Final Answer:
@Value("${app.name}") private String appName; -> Option BQuick Check:
Correct syntax uses ${} inside quotes = D [OK]
- Omitting quotes around the expression
- Forgetting the ${} around the property key
- Using plain property name without ${}
server.port=8080 in application.properties, what will be the output of this Spring component?public class ServerConfig {
@Value("${server.port}")
private int port;
public int getPort() {
return port;
}
}
// In main method:
ServerConfig config = new ServerConfig();
System.out.println(config.getPort());Solution
Step 1: Understand Spring bean lifecycle and injection
Property injection with@Valuehappens only when Spring creates and manages the bean. Here,ServerConfigis created manually withnew, so injection does not happen.Step 2: Check default value of int field
Sinceportis a primitive int and not injected, it defaults to 0.Final Answer:
0 -> Option AQuick Check:
Manual new means no injection, int defaults to 0 [OK]
- Assuming @Value works on manually created objects
- Expecting null for primitive int fields
- Ignoring Spring bean lifecycle
@Value("${missing.property}:defaultValue")
private String value;When
missing.property is not defined in properties, the application fails to start with an error.Solution
Step 1: Check default value syntax in @Value
The default value must be inside the quotes as part of the expression:@Value("${property:default}")is correct.Step 2: Identify the error cause
If the colon is outside quotes or expression is malformed, Spring cannot parse it and throws an error.Final Answer:
The default value syntax is incorrect; colon should be inside quotes -> Option CQuick Check:
Default values must be inside ${} quotes [OK]
- Placing colon outside the quotes
- Assuming default values are not supported
- Making fields public unnecessarily
app.modes=dev,prod,test into a Spring bean using @Value. Which approach correctly converts the property into a List<String>?Solution
Step 1: Understand property injection for collections
Spring does not automatically convert comma-separated strings to List<String> with plain @Value.Step 2: Use SpEL expression for conversion
@Value("#{T(java.util.Arrays).asList('${app.modes}'.split(','))}") private List<String> modes; uses Spring Expression Language (SpEL) to split the string and convert it to a List<String>, which is the correct approach.Final Answer:
@Value("#{T(java.util.Arrays).asList('${app.modes}'.split(','))}") private List<String> modes; -> Option AQuick Check:
Use SpEL split and asList for List injection [OK]
- Expecting automatic conversion from String to List
- Using array when List is required without conversion
- Injecting as String and forgetting to parse
Ready to prove it?
Pass the test and this pattern moves unknown
