set注入:设置值注入:spring调用类的set方法,完成属性赋值
peoperty:name:属性名
value:属性值
复杂类的注入
property name:属性名
ref=“bean”的id值
创建项目
导入jar包
编写School类和Student类
Student.java
package cn.lexed.pojo;
public class Student {
private String name;
private int age;
private School sc;//name address
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public School getSc() {
return sc;
}
public void setSc(School sc) {
this.sc = sc;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sc=" + sc + "]";
}
}
School.java
package cn.lexed.pojo;
public class School {
private String name;
private String address;
public School() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "School [name=" + name + ", address=" + address + "]";
}
}
编写配置文件
app.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">
<bean id="stus" class="cn.lexed.pojo.Student">
<!-- 简单类型 -->
<property name="name" value="张三"></property>
<property name="age" value="20"></property>
<!-- 引用类型 -->
<property name="sc" ref="sch"></property>
</bean>
<bean id="sch" class="cn.lexed.pojo.School">
<property name="name" value="南理工"></property>
<property name="address" value="秦淮区"></property>
</bean>
</beans>
编写测试类
TestSpring.java
package cn.lexed.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.lexed.pojo.Student;
public class TestSpring {
@Test
public void test() {
//1.创建Spring容器的对象
ApplicationContext ac=new ClassPathXmlApplicationContext("app.xml");
//2.使用getBean方法,getBean(配置文件中bean的id值)
Student s1=(Student)ac.getBean("stus");
System.out.println(s1);
}
}