阅读Spring源码之我见

我参考的并不是Spring source code,github上选择了mini-spring 这个项目。直接上项目:

 地址:https://github.com/DerekYRC/mini-spring.git

直接从test入手:

 

 1 public class ApplicationContextTest {
 2 
 3     @Test
 4     public void testApplicationContext() throws Exception {
 5         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml");
 6 
 7         Person person = applicationContext.getBean("person", Person.class);
 8         System.out.println(person);
 9         //name属性在CustomBeanFactoryPostProcessor中被修改为ivy
10         assertThat(person.getName()).isEqualTo("ivy");
11 
12         Car car = applicationContext.getBean("car", Car.class);
13         System.out.println(car);
14         //brand属性在CustomerBeanPostProcessor中被修改为lamborghini
15         assertThat(car.getBrand()).isEqualTo("lamborghini");
16     }
17 }
ApplicationContextTest

  1 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml")

注:此对象的是复杂对象,Spring在组织它的基础对象时,使用了非常精妙的设计。

 

 

 使用时序图工具,我们窥探下其中的调用层次:

 

 

 

 

 

其中的重要对象的创建分析如下:

 1      @Override
 2     public void refresh() throws BeansException {
 3         // 创建BeanFactory,并加载BeanDefinition
 4         refreshBeanFactory();
 5         ...
 6     }    
 7     protected abstract void refreshBeanFactory() throws     BeansException;
 8 
 9     在类AbstractRefreshableApplicationContext实现:
10     protected final void refreshBeanFactory() throws BeansException {
11         DefaultListableBeanFactory beanFactory = createBeanFactory();
12         loadBeanDefinitions(beanFactory);
13         this.beanFactory = beanFactory;
14     }
15 
16     protected DefaultListableBeanFactory createBeanFactory() {
17         return new DefaultListableBeanFactory();
18     }
DefaultListableBeanFactory

DefaultListableBeanFactory这个对象的继承体系我们通过UML观察下:

 

其中的细节信息一目了然

总结:UML与时序图的使用,是分析源码的重要手段,需要学以致用。

 

posted @ 2021-07-28 15:59  小白灬系  阅读(94)  评论(0)    收藏  举报