给属性赋值一般会使用这两个注解 @Value @PropertySource
1.@Value 赋值
1)基本数值
2) SpEL 表达式 #{}
3)${} 取出配置文件的值(在运行时环境变量中的值 Environment)
2.PropertySource 读取外部配置文件中的 key-value 保存到运行时环境变量中,加载完外部配置文件以后,使用 ${} 取配置文件中的值
举个小例子:
在配置文件 person.properties中有 person.nickName=小小丁
public class Person {
/**
* 使用 @Value 赋值
* 1.基本数值
* 2.SpEL 表达式 #{}
* 3.${} 取出配置文件的值(在运行环境变量中的值 Environment)
*/
@Value("小丁")
private String name;
@Value("#{27}")
private Integer age;
@Value("${person.nickName}")
private String nickName;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", nickName='" + nickName + '\'' +
'}';
}
}
@PropertySource(value = {"classpath:/person.properties"}, encoding = "utf-8")
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person() {
return new Person();
}
}
public class IOCTestPropertyValue {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
@Test
public void test01() {
printBeans(context);
Person person = (Person) context.getBean("person");
System.out.println("---->"+person);
ConfigurableEnvironment environment = context.getEnvironment();
String property = environment.getProperty("person.nickName");
System.out.println(property);
context.close();
}
private void printBeans(AnnotationConfigApplicationContext context) {
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String name : beanDefinitionNames) {
System.out.println(name);
}
}
}
输出结果: