在属性上使用@Value
package com.chentianyu.ba01;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component("myStudent")public class Student {/*** @Value: 简单类型的属性赋值* 属性: value 是String类型的,表示简单类型的属性值* 位置: 1.在属性定义上面,无需set方法,推荐使用* 2.在set方法的上面*/@Value(value = "张三")private String name;@Value(value = "29")private Integer 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;}*/@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}}
测试类
@Testpublic void test01(){String config = "applicationContext.xml";ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);//从容器中获取对象(需要id(value里的就是id))Student student = (Student) applicationContext.getBean("myStudent");System.out.println(student);}
Student{name='张三', age=29}
在set方法上使用@Value
package com.chentianyu.ba01;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("myStudent")
public class Student {
/**
* @Value: 简单类型的属性赋值
* 属性: value 是String类型的,表示简单类型的属性值
* 位置: 1.在属性定义上面,无需set方法,推荐使用
* 2.在set方法的上面
*/
private String name;
private Integer age;
public String getName() {
return name;
}
/*public void setName(String name) {
this.name = name;
}*/
public Integer getAge() {
return age;
}
@Value("30")
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Test
public void test01(){
String config = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
//从容器中获取对象(需要id(value里的就是id))
Student student = (Student) applicationContext.getBean("myStudent");
System.out.println(student);
}
Student{name='null', age=30}
getBean()底层是一个Map
