上期文章:
Spring源码分析系列(一)IOC容器的设计与实现(1)基础容器的实现
上一章我们讲了以xmlBeanFactory的方式实现的基础IOC容器,这回我们接着讲IOC容器的高级实现。首先先看下ApplicationContext的接口设计路线,他在继承了BeanFactory的基础上还集成了国际化接口MessageSource、资源获取ResourceLoader、事件机制ApplicationEventPublisher等,通过他们来实现基础容器做不到的高级特性。
下面我们来看三段代码
//通过实际路径
String xmlPath = "WebContent/WEB-INF/config/base/applicationContext.xml";
ApplicationContext ac = new FileSystemXmlApplicationContext(xmlPath);
user = ac.getBean(test.class);
//通过根目录默认
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
user = ac.getBean(LsjmUserServiceImpl.class);
//通过xmlwebApplication
ServletContext servletContext =request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
这三种方式都可以获取到ApplicationContext对象,我们以FileSystemXmlApplicationContext举例。
首先是初始化,执行构造方法,然后按照继承链进行父类初始化,最后refresh启动。
继承链上的父类包括:
AbstractXmlApplicationContext
AbstractRefreshableConfigApplicationContext
AbstractRefreshableApplicationContext
AbstractApplicationContext
public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{configLocation}, true, (ApplicationContext)null);
}
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
我们继续跟进refresh方法,在AbstractApplicationContext类中看到了他的实现,这里是容器的准备阶段,调用了ConfigurableListableBeanFactory接口,那谁是他的实现类呢?我们接着往下走。
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
}
}
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory();
return this.getBeanFactory();
}
我们通过refreshBeanFactory继续执行,通过AbstractApplicationContext的继承体系,我们在AbstractRefreshableApplicationContext类中找到了他的实现方法。看他的逻辑,先容器校验是否创建,存在就销毁。然后我们还是通过构建实体类DefaultListableBeanFactory来实现容器,这个我们后续会讲解如何实现。
通过这段代码,我们发现:
无论是BeanFactory体系的基础容器,还是ApplicationContext体系的高级容器,我们是要通过DefaultListableBeanFactory来实现。
protected final void refreshBeanFactory() throws Exception {
if (this.hasBeanFactory()) {
this.destroyBeans();
this.closeBeanFactory();
}
DefaultListableBeanFactory beanFactory = this.createBeanFactory();
beanFactory.setSerializationId(this.getId());
this.customizeBeanFactory(beanFactory);
this.loadBeanDefinitions(beanFactory);
synchronized(this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
根据基础容器的构建方式可知,要实现容器首先要将xml中的结构,解析出来装载到CurrentHashMap
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = this.getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = this.getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
进入到AbstractBeanDefinitionReader类中,然后获取资源加载器ResourceLoader根据ResourceLoader的类型不同对资源有不同的获取方法当为ResourcePatternResolver类型时,将ResourceLoader强转类型后调用getResource()方法定位资源否则,直接调用DefaultResourceLoader的getResource()方法定位资源。
public int loadBeanDefinitions(String location, @Nullable Set actualResources) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = this.getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException("Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
} else {
int count;
if (resourceLoader instanceof ResourcePatternResolver) {
Resource[] resources = ((ResourcePatternResolver)resourceLoader).getResources(location);
count = this.loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
return count;
} else {
Resource resource = resourceLoader.getResource(location);
count = this.loadBeanDefinitions((Resource)resource);
if (actualResources != null) {
actualResources.add(resource);
}
}
return count;
}
}
}
进入到DefaultResourceLoader类,getResource里会判断传入的路径类型,是根目录标识的定位,还是Url标识的定位,还是是实际路径标识的定位。FileSystemXmlApplicationContext属于实际路径所以我们继续执行getResourceByPath方法。
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
Iterator var2 = this.protocolResolvers.iterator();
Resource resource;
do {
if (!var2.hasNext()) {
if (location.startsWith("/")) {
return this.getResourceByPath(location);
}
if (location.startsWith("classpath:")) {
return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());
}
try {
URL url = new URL(location);
return (Resource)(ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
} catch (MalformedURLException var5) {
return this.getResourceByPath(location);
}
}
ProtocolResolver protocolResolver = (ProtocolResolver)var2.next();
resource = protocolResolver.resolve(location, this);
} while(resource == null);
return resource;
}
getResourceByPath的实现类就在我们最开始的入口FileSystemXmlApplicationContext类中,这个方法会返回一个FileSystemResource对象,通过这个对象Spring就可以进行I/O操作完成BeanDefinition定位。
protected Resource getResourceByPath(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
经过上述操作我们完成了配置资源的定位工作,接下就是BeanDefinition的载入和解析。
让我们回到AbstractBeanDefinitionReader类中的loadBeanDefinitions(String , Set
Resource resource = resourceLoader.getResource(location);
count = this.loadBeanDefinitions((Resource)resource);
继续追踪代码在BeanDefinitionReader接口中我们按照xml解析的方式选择XmlBeanDefinitionReader作为实现类,这里将resource对象转换为流并通过doLoadBeanDefinitions方法进行读取。具体的读取过程都在doLoadDocument中,最后将读取的结果放入Document对象中并开始注册。
public int loadBeanDefinitions(EncodedResource encodedResource) {
InputStream inputStream = encodedResource.getResource().getInputStream();
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
var5 = this.doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) {
// 具体的读取过程都在doLoadDocument中
Document doc = this.doLoadDocument(inputSource, resource);
int count = this.registerBeanDefinitions(doc, resource);
return count;
}
我们继续跟进代码registerBeanDefinitions,我们发现registerBeanDefinitions真正的实现类又回到了我们在注册基础容器时用到的DefaultBeanDefinitionDocumentReader类。后续的注册过程就不在叙述,参考基础容器的实现,高级容器与基础容器的的核心本质上都是一套东西。
最后关于AppliicationContext的高级特性部分,我们往回找,找到AbstractApplicationContext看refresh方法。在准备好基础的IOC容器后,我们开始逐步注册那些高级特性。
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
// 启动注册ioc容器
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
// 初始化消息
this.initMessageSource();
// 初始化时间机制
this.initApplicationEventMulticaster();
this.onRefresh();
//注册监听器
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
}
}