我今天学习到了 SpringBoot 的属性赋值 @Value 用法,先总结:
@Value(" 张三 ") :直接附在属性名上,在 Bean 初始化时,会赋初始值
@Value(" #{ 20 - 2 } ") :可以用 #{ } ,里面可以写表达式,当然也可以直接 @Value(" #{ 18 } ") 或 @Value(" 18 ")
@Value(" ${ person.name } ") :利用 ${ } 可以取出配置文件中的值
例子:
配置类:
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person() {
return new Person();
}
}
@Configuration:告诉 Spring 这是一个配置类
@PropertySource:关联配置文件,使用 @PropertySource 指定读取外部配置文件,保存到运行的环境变量中,然后可以用 @Value(" ${ person.name } ") 获取环境变量中的值。
Bean :
public class Person {
/*
* 使用@Value赋值:
* 1. 基本数值
* 2. 可以写 #{ }
* 3. 可以写 ${ },取出配置文件{properties}中的值
*/
@Value("张三")
private String name;
@Value("#{20-2}")
private int age;
@Value("${person.nickName}")
private String nickName;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", nickName=" + nickName + "]";
}
public Person(String name, int age, String nickName) {
super();
this.name = name;
this.age = age;
this.nickName = nickName;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
}
配置文件:
person.nickName=\u5C0F\u4E09
这里面的 \u5C0F\u4E09 表示的是“小三”
而配置文件的位置:
运行:
public class IOCTest_PropertyValue {
//容器创建
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
//打印容器中Bean的name
private void printBeans(AnnotationConfigApplicationContext applicationContext) {
String[] definitionName = applicationContext.getBeanDefinitionNames();
for(String name : definitionName) {
System.out.println(name);
}
}
@Test
public void test01() {
printBeans(applicationContext);
System.out.println("-------------------------------------------------------");
//获得容器中的Person
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
//获得环境变量中的值
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.nickName");
System.out.println("环境变量:"+property);
applicationContext.close();
}
}
运行结果: