1.使用set方法存放类的属性
(1)类:
public class Student {
private int stuNo;
private String stuName;
private int stuAge;
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
(2)IOC容器的配置:
<bean id="student" class="org.wpc.entity.Student" >
<!-- property:该class所代表的类的属性
name:属性名
value:属性值
-->
<property name="stuNo" value="2"></property>
<property name="stuName" value="ls"></property>
<property name="stuAge" value="24"></property>
</bean>
(3)获取配置完的类
//Spring上下文对象:context
ApplicationContext context = new ClassPathXmlApplicationContext("org/wpc/xml/applicationContext.xml");
//执行springIOC容器中获取一个id为student的对象
Student student = (Student) context.getBean("student");
2.利用构造器放置类的属性
(1)类
public class Student {
private int stuNo;
private String stuName;
private int stuAge;
public Student(int stuNo, String stuName, int stuAge) {
this.stuNo = stuNo;
this.stuName = stuName;
this.stuAge = stuAge;
}
}
(2)IOC容器的配置:
<bean id="student" class="org.wpc.entity.Student" >
<constructor-arg value="ls" name="stuName"></constructor-arg>
<constructor-arg value="1" name="stuAge"></constructor-arg>
<constructor-arg value="24" name="stuNo"></constructor-arg>
</bean>
(3)获取配置完的类
//Spring上下文对象:context
ApplicationContext context = new ClassPathXmlApplicationContext("org/wpc/xml/applicationContext.xml");
//执行springIOC容器中获取一个id为student的对象
Student student = (Student) context.getBean("student");
3.配置的类的属性存在引用类
(1)类:
public class Student {
private int stuNo;
private String stuName;
private int stuAge;
private Teacher stuTeacher;
public Teacher getStuTeacher() {
return stuTeacher;
}
public void setStuTeacher(Teacher stuTeacher) {
this.StuTeacher = stuTeacher;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
(2)IOC容器的配置:
<bean id="student" class="org.wpc.entity.Student" >
<!-- property:该class所代表的类的属性
name:属性名
value:属性值
-->
<property name="stuNo" value="2"></property>
<property name="stuName" value="ls"></property>
<property name="stuAge" value="24"></property>
<!-- 使用ref对属性类进行引用 -->
<property name="stuTeacher" ref="teacher"></property>
</bean>
(3)获取配置完的类
//Spring上下文对象:context
ApplicationContext context = new ClassPathXmlApplicationContext("org/wpc/xml/applicationContext.xml");
//执行springIOC容器中获取一个id为student的对象
Student student = (Student) context.getBean("student");