@Value Annotation in Spring: What It Is and How to Use It
@Value annotation in Spring is used to inject values into fields, methods, or constructor parameters from property files, environment variables, or expressions. It helps configure components by providing external values without hardcoding them in the code.How It Works
The @Value annotation works like a label that tells Spring to fill a variable with a value from outside the code. Imagine you have a recipe and want to change the amount of sugar without rewriting the recipe every time. Instead, you keep the sugar amount in a separate note (a property file), and the recipe reads from that note when cooking.
Spring reads the value from places like property files (application.properties or application.yml), environment variables, or even expressions. When the application starts, Spring finds the @Value annotation and replaces the variable with the actual value. This makes your code flexible and easy to change without touching the source code.
Example
This example shows how to use @Value to inject a property value into a Spring component.
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GreetingService { @Value("${greeting.message}") private String message; public void greet() { System.out.println(message); } } // application.properties // greeting.message=Hello, welcome to Spring!
When to Use
Use @Value when you want to keep configuration or constant values outside your code for easy changes. For example, you can inject database URLs, API keys, or messages that might change depending on the environment (development, testing, production).
This helps avoid hardcoding values and supports different setups without changing the code. It is especially useful for settings that vary between deployments or need to be kept secret.
Key Points
- @Value injects external values into Spring-managed beans.
- Values can come from property files, environment variables, or expressions.
- It improves flexibility by separating configuration from code.
- Supports simple expressions and default values.
Key Takeaways
@Value injects external configuration values into Spring components.