@Value的作用是通过注解将常量、配置文件中的值、其他bean的属性值注入到变量中,作为变量的初始值。
- @Value():注入基础数据类型。
- @Value("#{}") :表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法,也可以表示常量。当bean通过@Value(“#{}”) 获取其他bean的属性,或者调用其他bean的方法时,只要该bean (Beab_A)能够访问到被调用的bean(Beab_B),即要么Beab_A 和Beab_B在同一个容器中,或者Beab_B所在容器是Beab_A所在容器的父容器。
- @Value(" " ) : 通 过 @ V a l u e ( " {}"):通过@Value(" "):通过@Value("{}") 可以获取对应属性文件中定义的属性值。
实体类:
public class Person {
@Value("张三")
private String name;
@Value("#{2*11}")
private Integer age;
@Value("${hobby}")
private String hobby;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
创建一个属性文件person.properties
hobby=看电影
配合类:
// 使用@PropertySource读取外部配置文件中K-V保存到运行环境中;之后再使用${}来读取出配置文件的值
@PropertySource(value="classpath:/person.properties")
@Configuration//声明这是一个配置类
public class MyConfig {
//创建Bean
@Bean
public Person person() {
return new Person();
}
}
测试方法:
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
Person person = (Person) applicationContext.getBean("person");
System.out.println(person.toString());
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("hobby");
System.out.println(property);
}
结果:
Person[name="张三", age=22 , hobby="看电影"]
看电影