In this post under Spring Core, I will show with example how to use “@Value” annotation.
In previous post I showed how to access system properties, environment properties, custom properties using “Environment” interface.
In all these case we had to explicitly retrieve the value as shown below and are not injected into the bean automatically by the Spring framework.
getEnvironment().getProperty("name");
That is where “@Value” annotation comes into picture.
This annotation is applied at the field level and once applied, the Spring framework will retrieve the value from appropriate source and set the field value to the retrieved value.
Below is the complete code for your reference.
Main class
1 package core.package38;
2
3 import org.springframework.beans.factory.annotation.Value;
4 import org.springframework.context.ApplicationContext;
5 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6 import org.springframework.context.annotation.Configuration;
7 import org.springframework.context.annotation.PropertySource;
8
9 @Configuration
10 @PropertySource("app1.properties")
11 public class Example38 {
12 @Value("${java.vendor}")
13 private String environment;
14 @Value("${OS}")
15 private String osname;
16 @Value("${name}")
17 private String name;
18 @Value("${hello:welcome}")
19 private String message;
20
21 public void display() {
22 System.out.println(environment);
23 System.out.println(osname);
24 System.out.println(name);
25 System.out.println(message);
26 }
27
28 public static void main(String[] args) {
29 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example38.class);
30 Example38 example35 = applicationContext.getBean(Example38.class);
31 example35.display();
32 }
33 }
In the above code, I have annotated the fields “environment”, “osname”, “name”, and “message” with “@Value” annotation. Refer to line 12, 14, 16, and 18.
The property name to be retrieved is placed between “${” and “}” and passed as String argument to the “@Value” annotation. Refer to line 12, 14, 16, and 18.
The Spring framework will retrieve the value using the property name from appropriate source and inject the value to the bean fields.
One more thing, if a property doesn’t exist in any of the source mentioned, the field value is set to null. To avoid that we can provide a default value as shown at line 18.
To set the default value for a bean field, you should pass the property name and the default value both within “${” and “}” seperated by “:” as an argument to “@Value” annotation as shown at line 18
At line 18, since there is no property by name “hello” in system, environment, or custom property file, the default value “welcome” is set to “message” field.
In this way we can use “@Value” annotation.