mini-springframework主要是简化了Spring设计,用于增加对Spring架构设计的理解而开发的,代码托管在Github:https://github.com/wenbo2018/mini-springframework
mini-springframework是对Spring的简化实现,Spring代码过于繁杂如果想全面阅读比较困难,mini-springframework简化了Spring实现 同时保持了Spring启动过程中的重要环节,有利于加深的Spring架构设计理解。目前实现了一下几种功能:
1.基于XML方式配置Bean
设计原理:
1.ApplicatioContext设计
ApplicatioContext作为Spring中最终的IOC接口,有着非常重要的作用,本文根据编程方式创建Spring IOC容器来实现简化版SpringIOC,最终使用的是下面代码:
public static void main(String[] args) throws Exception {
BeanFactory beanFactory = new FileSystemXmlApplicationContext("minispringframework.xml");
UserService userService = (UserService) beanFactory.getBean("userService");
userService.hello();
}
以FileSystemXmlApplicationContext作为切入口来分析Spring启动过程,其继承体系如下:
FileSystemXmlApplicationContext内部的代码很简单,主要起初始化调用refresh()方法作用:
public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
public FileSystemXmlApplicationContext() {
}
public FileSystemXmlApplicationContext(ApplicationContext parent) {
super(parent);
}
public FileSystemXmlApplicationContext(String configLocation) throws Exception {
this(new String[]{configLocation}, true, null);
}
public FileSystemXmlApplicationContext(String... configLocations) throws Exception {
this(configLocations, true, null);
}
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws Exception {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
}
refresh()方法中主要包括三个方法:
DefaultListableBeanFactory beanFactory = obtainFreshBeanFactory();获取BeanFactory
loadBeanDefinitions(beanFactory);//载入BeanDefinition
registerBeanPostProcessors(beanFactory);//注册BeanPostProcessors
真实Spring中这个方法中会有很多个步骤,我们只是抽取其中几个重要的步骤。
protected void refresh() throws Exception {
DefaultListableBeanFactory beanFactory = obtainFreshBeanFactory();
loadBeanDefinitions(beanFactory);
registerBeanPostProcessors(beanFactory);
}