Below are some common ways to use the @Value annotation in Spring:
@Value("${property.name}")
private String propertyValue;
Here, property.name is a key in application.properties or application.yml, and the value of this key will be injected. @Value("${ENV_VAR_NAME}")
private String envVariable;
This will inject the value of the environment variable named ENV_VAR_NAME. @Value("#{systemProperties['user.name']}")
private String systemUser;
This will inject the value of the system property user.name. @Value("#{2 + 2}")
private int calculatedValue; // Injects 4
@Value("Deepak")
private String name;
This will inject the literal string "Deepak" in name variable. public MyClass(@Value("${property.name}") String propertyValue) {
this.propertyValue = propertyValue;
}
This will inject the value of the system property user.name. @Autowired
public void setSomeValue(@Value("${property.name}") String propertyValue) {
this.propertyValue = propertyValue;
}
This will inject the value of the system property user.name.
Below is the program demonstrates how to set static value using @Value annotation.
package in.sp.beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Student
{
@Value("Deepak")
private String name;
@Value("101")
private int rollno;
@Value("deepak@gmail.com")
private String emailid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public void display()
{
System.out.println("Name : "+name);
System.out.println("Roll No : "+rollno);
System.out.println("Email Id : "+emailid);
}
}
package in.sp.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import in.sp.beans.Student;
@Configuration
@ComponentScan(basePackages = "in.sp.beans")
public class MainApp
{
public static void main(String[] args)
{
// Spring container is created with MainApp as configuration class
ApplicationContext context = new AnnotationConfigApplicationContext(MainApp.class);
// Bean object is requested from Spring Container and stored in Student reference
Student std = context.getBean(Student.class);
std.display();
}
}
Below is the output
Name : Deepak Roll No : 101 Email Id : deepak@gmail.com
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.