import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Greeting {
@Value("${app.greeting}")
private String message;
public String getMessage() {
return message;
}
}If the application.properties contains
app.greeting=Hello, Spring!, what will getMessage() return?The @Value annotation injects the property value from application.properties into the field. Since app.greeting=Hello, Spring! is defined, message will hold that string.
app.name but provide a default value "MyApp" if the property is missing. Which @Value syntax is correct?The correct syntax to provide a default value in @Value is ${property:defaultValue}. So @Value("${app.name:MyApp}") injects the property or "MyApp" if missing.
@Component
public class Config {
@Value("${app.timeout}")
private Integer timeout;
public int getTimeout() {
return timeout;
}
}and
app.timeout is not set in properties, what causes a NullPointerException when calling getTimeout()?If the property is missing, Spring injects null into the Integer field. When getTimeout() returns int (primitive), Java tries to unbox null to int, causing NullPointerException.
@Component
public class StaticConfig {
@Value("${app.version}")
private static String version;
public static String getVersion() {
return version;
}
}What will be the behavior of the
version field?Spring injects values into instance fields during bean creation. Static fields belong to the class, not the instance, so @Value does not inject into static fields. The field remains null.
@Component
public class Calculator {
@Value("#{2 * 3 + 4}")
private int result;
public int getResult() {
return result;
}
}What will
getResult() return?The expression inside SpEL is 2 * 3 + 4. Multiplication happens first: 2*3=6, then add 4 = 10. So result is 10.