属性赋值 01 @Value赋值
传统方式
public class Person {
private String name;
private Integer age;
private String nickName;
public Person() {
}
public Person(String name, Integer age, String nickName) {
this.name = name;
this.age = age;
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;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", nickName='" + nickName + '\'' +
'}';
}
}
beans.xml
<context:property-placeholder location="classpath:person.properties" />
<bean id="person4PropertyValues" class="com.example.annotations.bean.Person">
<property name="age" value="21"/>
<property name="name" value="qd"/>
<property name="nickName" value="${person.nickName}"/>
</bean>
配置文件
person.properties
person.nickName=Aimer
测试
@Test
void xmlPropertyValuesTest(){
//传统方式
ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
System.out.println("容器创建完毕");
//获取bean
System.out.println("准备获取bean");
Object person4PropertyValues = xmlApplicationContext.getBean("person4PropertyValues");
System.out.println(person4PropertyValues.toString());
System.out.println("获取完毕");
//关闭容器
xmlApplicationContext.close();
System.out.println("容器已关闭");
}
运行结果:
注解方式
- 基本数值
- SPEL表达式 : #{22-1} => 21
- ${} :取出配置文件的值 [在运行环境变量中的值]
Person.java
public class Person {
@Value("qd")
private String name;
@Value("#{22-1}")
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
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 getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
配置类
@Configuration
public class MainConfig4PropertyValues {
@Bean("person4PropertyValues")
public Person person(){
return new Person();
}
}
测试
@Test
void propertyValuesTest(){
//配置类测试
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig4PropertyValues.class);
System.out.println("容器创建完毕");
//获取bean
System.out.println("准备获取bean");
Object person4PropertyValues = applicationContext.getBean("person4PropertyValues");
System.out.println(person4PropertyValues.toString());
System.out.println("获取完毕");
//关闭容器
applicationContext.close();
System.out.println("容器已关闭");
}
运行结果
注意 无论是beans.xml 还是配置类 都要保证bean的名字不重复