How to use @Value in Spring?
In Spring, the @Value annotation can be used to inject property values into variables. It can be used to inject values of simple types, read values from property files, and read values from environment variables.
Here is how the @Value annotation is used:
- Injecting simple type property values:
@Value("Hello World!")
private String message;
- Read property values from a properties file.
@Value("${app.name}")
private String appName;
In the example above, ${app.name} is a property name in the property file and will be replaced with the corresponding property value in the file.
- Read property values from the environment variables.
@Value("${JAVA_HOME}")
private String javaHome;
In the example above, ${JAVA_HOME} is the name of an environment variable that will be replaced with its corresponding value.
It is important to note that the @Value annotation can be used to inject values of any simple type property, including strings, numbers, booleans, etc. If the property value to be injected does not exist, an exception will be thrown. If a default value needs to be set, it can be specified by using the format @Value(“${app.name:default}”).
In addition, the @Value annotation can also be used for constructor arguments, method parameters, and method return values to achieve property value injection.