Spring5源码解析-Bean的初始化
Spring5源码解析-Bean的初始化
1.工程搭建
在spring-beans工程上添加测试代码
目录结构:
java类源码:
/**
- @author wufei
- @create 2019-02-15 9:08
**/
public class MyTestBean {
private String testStr = “testStr”;
public String getTestStr() {
System.out.println(“执行getTestStr方法”);
return testStr;
}
public void setTestStr(String testStr) {
this.testStr = testStr;
}
}
public class BeanFactoryTest {
@Test
public void test(){
System.out.println(“exec”);
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(“wftest.xml”, getClass()));
MyTestBean myTestBean = (MyTestBean) beanFactory.getBean(“myTestBean”);
myTestBean.getTestStr();
}
}
xml配置文件:
运行
2.功能分析
spring帮我们完成了什么工作呢? 大胆的猜想阅读源码。
1.读取配置文件(wftest.xml)
2.根据配置文件中的配置找到对应的类的配置,并实例化。
3.调用实例化后的实例。
3.核心类介绍
spring核心的两个类
1.DefaultListableBeanFactory
2. XmlBeanDefinitionReader
源码解析:
对xml的配置文件的解析
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(“wftest.xml”, getClass()));
bean的加载
MyTestBean myTestBean = (MyTestBean) beanFactory.getBean(“myTestBean”);
bean的创建
spring如何解决循环依赖
依赖处理:
在Spring中会有循环依赖的情况,例如:当A中含有B中的属性,B中有含有A的属性时就构成一个循环依赖,此时如果A和B都是单例,那么在Spring中的处理方式就是当创建B的时候,涉及自动注入A的步骤时,并不是直接去再此创建A,而是通过放入缓存中的ObjectFactory来创建实例,这样就解决了循环依赖的问题。(在spring中解决循环依赖只对单例有效)
spring实例化