0%

spring源码中的设计模式

spring源码中的设计模式

spring源码中的设计模式

策略模式,代理模式,单例模式,模板方法模式

策略模式

策略模式

Spring源码中如何使用

  • 加载xml文件。AbstractApplicationContext的refresh方法的第二步。加载xml文件,bean定义读取器BeanDefinitionReader中,资源加载器ResourceLoader、bean名称生成器(BeanNameGenerator),使用了策略模式。ClassPathXmlApplicationContext、FileSystemXmlApplicationContext(覆盖了方法Resource getResourceByPath(String path))是DefaultResource的子孙类,表示两种加载xml文件的策略:类路径、系统路径。
  • AOP代理。代理类AopProxy,有JdkDynamicAopProxy和CglibAopProxy两个实现类。
  • template的实现。JDBCTemplate,HibernateTemplate。

代理模式

代理模式:AOP用代理模式实现。

目的:对业务代码做前置处理,增加日志

Spring源码如何使用

  • JDK动态代理,需实现接口
  • CGLib代理,直接给字节码加代码

单例模式

单例模式:类只有单个对象会被创建(实例化),向其他类只提供一种访问方式。可以全局访问.

spring源码如何使用

用到了双重校验锁。支持多线程,有lazy loading效果。

第一个if (singletonObject== null),singletonObject没有被实例化时,对实例化内容加锁。避免非必要加锁。

第二个if (singletonObject== null),第一次实例化singletonObject时,防止多个线程在synchronized处等待并执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}

模板方法模式

模板方法:定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。

spring源码如何使用

AbstractApplicationContext的refresh方法定义了初始化容器的流程。只是写了一个个流程的方法。

1.刷新预处理,重置容器的一些信息

2.创建容器,加载xml信息到BeanDefinition

3.对IOC容器进行预处理

11.实例化开发者配置的非抽象非延迟加载的单例Bean。

12.发步相应的事件。