目录
前言
这篇文章是 IOC
容器初始化启动时,抽象类 AbstractAutowireCapableBeanFactory
的 doCreateBean()
方法里面的 populateBean()
方法,它是进行 bean
的属性数据填充注入的方法
阅读本篇文章,同时可以参考阅读 spring源码之getBean(获取 bean)方法解读(二) 和 Spring Aop代理对象的产生(一) 这两篇文章的 doCreateBean()
方法
测试代码
Java
实体
public class Teacher {
private Student student;
public Teacher() {
System.out.println("Teacher 的无参构造器被调用了");
}
public Teacher(Student student) {
System.out.println("Teacher 的有参构造器被调用了");
this.student = student;
}
public void echo() {
System.out.println("I'm a student : " + student);
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@Override
public String toString() {
return "Teacher{" +
"student=" + student +
'}';
}
}
public class Student {
private String name;
public Student() {
System.out.println("Student 的无参构造器被调用了");
}
public Student(String name) {
System.out.println("Student 的有参构造器被调用了");
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
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="student" class="com.atguigu.pojo.Student">
<property name="name" value="小吉"></property>
</bean>
<bean id="teacher" class="com.atguigu.pojo.Teacher" autowire="byType">
<!-- <property name="student" ref="student"></property>-->
</bean>
</beans>
测试类
public class Test2 {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-spring.xml");
Teacher teacher = (Teacher) applicationContext.getBean("teacher")