使用@Value对bean实例的属性赋值,此注解可直接修饰属性,主要分三种情况:
1、基本数值直接赋值
2、可以写SpEL:#{}表达式通过运算进行赋值
3、可以写${};取出配置文件【xxx.properties】中的值(在运行环境变量里面的值)进行赋值;
public class Person {
@Value("Fangxinde")//属性name直接赋值
private String name;
@Value("#{35-2}")//通过表达式对属性age赋值
private Integer age;
@Value("${person.nickName}")//获取配置文件中值对属性nickName进行赋值
private String nickName;
//===================set、get方法省略====================
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", nickName="
+ nickName + "]";
}
}
配置类:
@PropertySource中value值是配置文件的路径,把配置文件注册到容器,注解@Value("${person.nickName}")才能获取配置文件中的值
@PropertySource(value={"classpath:/person.properties"})//配置类中引入配置文件
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
System.out.println("创建bean");
return new Person();
}
}
配置文件person.properties
public class IOCTest_PropertyValue {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
@SuppressWarnings("resource")
@Test
public void test01(){
System.out.println("容器创建完成.....");
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
applicationContext.close();
}
}
运行结果:
Person [name=Fangxinde, age=33, nickName=李次方]