ApplicationContext.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--声明student对象
注入:就是赋值的意思
简单类型: spring中规定Java的基本数据类型和String都是简单类型。
di:给属性赋值
1.set注入(设置注入):spring 调用类的set方法,你可以在set方法中完成属性的赋值
1.简单类型的set注入
<bean id = "xx" class="yy">
<property name ="属性名字“ values = "此属性的值“/>
</bean>
一个property只能给一个属性赋值
<property...>
2.引用类型的set注入: spring调用类的set方法
<bean id = "xx" class="yy">
<property name ="属性名字“ ref = "bean的id(对象的名称)“/>
</bean>
-->
<bean id="Student" class="cn.qiang.service.ba02.Student">
<property name="name" value="李四"/> <!-- setName:("李四")-->
<property name="age" value="12"/> <!-- setAge:(12)-->
<property name="email" value="lisi@qq.com"/>
<!-- 引用类型的-->
<property name="school" ref="mySchool"/>
</bean>
<bean id="mySchool" class="cn.qiang.service.ba02.School">
<property name="name" value="南京大学"/>
<property name="address" value="南京"/>
</bean>
</beans>
Student 和School 类
package cn.qiang.service.ba02;
public class School {
private String name;
private String address;
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
package cn.qiang.service.ba02;
public class Student {
private String name;
private int age;
//声明一个引用类型
private School school;
public void setSchool(School school) {
System.out.println("setSchool:"+school);
this.school = school;
}
public void setName(String name) {
System.out.println("setName:"+name);
this.name = name;
}
public void setAge(int age) {
System.out.println("setAge:"+age);
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
public void setEmail(String email){
System.out.println("setEmail:"+email);
}
}
测试类
package com.qiang;
import cn.qiang.service.ba02.School;
import cn.qiang.service.ba02.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest02 {
@Test
public void test01(){
Student student = new Student();
student.setName("李四");
student.setAge(20);
School school = new School();
school.setName("马鞍山学院");
school.setAddress("马鞍山");
student.setSchool(school);
System.out.println("Student:"+student);
}
@Test
public void test02(){
String config = "ba02/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
Student mystudent = (Student) ac.getBean("Student");
System.out.println("Student:" +mystudent);
}
}