@Value 作用是给类的属性赋值的。
三种使用方法:1.基本字符;2.springEL表达式;3.读取配置文件中的内容
首先在src/main/resources下建立一个文件test.properties
然后在配置类中配置路径
@Configuration
@PropertySource("classpath:/test.properties")
public class MainConfig8 {
@Bean
public Person person(){
return new Person();
}
}
public class Person {
//@Value 三种使用方法:1.基本字符;2.springEL表达式;3.读取配置文件中的内容
@Value("dapeng")
private String name;
@Value("#{30-5}")
private Integer age;
@Value("${person.height}")
private Float height;
public Person() {
}
public Person(String name, Integer age, Float height) {
this.name = name;
this.age = age;
this.height = height;
}
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 Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
}
测试:
@Test
public void test01() {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(MainConfig8.class);
System.out.println("容器加载完成 。。。");
Person person = (Person) app.getBean("person");
System.out.println(person);
String height = app.getEnvironment().getProperty("person.height");
System.out.println("Environment --> person.height="+height);
}
测试结果: