三、属性赋值
1.直接赋值 @value
Person类
**
* @author GaoYuzhe
* @date 2018/3/12.
*/
public class Person {
//属性赋值
@Value("daxiong")
private String name;
@Value("18")
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
//.....省略set get
}
注册类 PropertyConfig
@Configuration
public class PropertyConfig {
@Bean
public Person person(){
return new Person();
}
}
测试类
public class PropertyConfigTest {
@Test
public void person() {
AnnotationConfigApplicationContext annotationConfigApplicationContext= new AnnotationConfigApplicationContext(PropertyConfig.class);
Person person = (Person) annotationConfigApplicationContext.getBean("person");
System.out.println(person);
}
运行结果
2.@Value配置文件赋值
添加配置文件 person.properties
person.name = daxiong
person.age=18
修改Person类的注解取值
//可以写${}取perperties 中的值(其实是在运行环境变量【Enviroment】中取的值)
@Value("${person.name}")
private String name;
//SpEL #{}取值并计算
@Value("#{${person.age}*2}")
private Integer age;
配置类加上注解@PropertySource
@PropertySource("classpath:/person.properties")
运行结果
从Enviroment中取值
ConfigurableEnvironment environment = annotationConfigApplicationContext.getEnvironment();
String personAge = environment.getProperty("person.age");
System.out.println(personAge);