@Value注解的主要作用是给变量赋初始值,设置@Value的初始值有三种不同的方式。第一,直接赋值。第二,赋值为SpEL表达式,运算后把值赋值给变量。第三,从配置文件里面获取值再赋给变量。
通过观察源码,可以发现@Vlaue注解的作用对象比较广:@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
- 创建类并且演示@Value的三种用法:
import org.springframework.beans.factory.annotation.Value;
public class Student {
//直接赋初值
@Value(value = "Nobody")
private String name;
//从配置文件中获取值再赋给变量
@Value("${student.ID}")
private String ID;
//使用SpEL表达式,计算后再赋值
@Value(value = "#{2-2}")
private Integer age;
public void initial(){
System.err.println("The initial method is calling.");
}
public void destroy(){
System.err.println("The destroy method is calling.");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", ID='" + ID + '\'' +
", age=" + age +
'}';
}
}
- 在resources文件夹中的application.properties(没有的话,自己创建)中创建键值对:
student.ID = "s-00"
- 通过@PropertySource注解设置配置信息文件,Spring Boo项目默认application.properties为配置信息文件:
import com.michael.annotation.demo.POJO.Student;
import org.springframework.context.annotation.*;
@Configuration
@PropertySource(value = {"classpath:/application.properties"})
public class MyConfig {
@Scope("singleton")
@Bean(value = "s1")
public Student student(){
return new Student();
}
}
- 测试代码:
import com.michael.annotation.demo.POJO.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
out.println(((Student)applicationContext.getBean("s1")).toString());
}
}
- 输出:
Student{name='Nobody', ID='"s-00"', age=0}
- 从输出可以看到,Student对象的属性被默认赋值。