本文知识点来源于尚硅谷,感谢尚硅谷为广大学子提供的优质教育资源,感谢各位老师热情指导,本文仅作为学习笔记使用,记录学习心得,如有不适,请联系作者。
新增person.properties文件
person.sex=\u5973
测试Bean如下:
public class Person {
//注入普通字符串
@Value("张三")
private String name;
//使用SpEL表达式注入属性
@Value("#{10*2}")
private Integer age;
//获取对应属性文件中定义的属性值
@Value("${person.sex}")
private String sex;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, Integer age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
配置类:
@PropertySource({“classpath:/person.properties”}) //读取外部配置文件中的key/value保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置稳健的值
@Configuration
@PropertySource({"classpath:/person.properties"}) //读取外部配置文件中的key/value保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置稳健的值
public class MainConfigOfPropertyValues {
@Bean
public Person person() {
return new Person();
}
}
测试类:
public class MainTest_PropertyValues {
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
//获取配置文件中的值
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.sex");
System.out.println(property);
}
}
输出:
Person [name=张三, age=20, sex=女]
女