-
BeanFactory和ApplicationContext
BeanFactory和ApplicationContext都是容器,BeanFactory是最基础的容器,里面定义了一些最基本的方法:
而Application也同样是容器,对比与BeanFactory来说,是一个相对比较高级的容器。
-
IOC主要接口设计图
可以看出像WebApplicationContext这种高级的容器都是通过继承等关系,符合标准容器的规范,然后拓展自己想要的高级功能。
-
BeanDefinition
这个接口描述bean的结构,对应XML中的< bean >或者配置类中的@Bean,比如:
其拓展的子类如XMLBeanDefinition,AnnotationBeanDefinition等等,就是分别以不同形式来定义bean的信息,如上图所示就是以XML结构来定义Bean的信息。
-
BeanDefinitionReader
用来解析bean的信息的类,比如一个具体实现类XMLBeanDefinitionReader就是用来解析XML形式定义的bean
-
编程式使用Ioc容器
ClassPathResource res = new ClassPathResource("bean.xml"); // 读取存储Bean信息的资源
DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); // 创建一个ioc容器
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); // 创建一个xml文件形式的BeanDefinition的读取器
reader.loadBeanDefinitions(res); // 装在bean配置信息
-
Ioc容器的初始化过程
1)Resource定位过程
首先定义一个Resource来定位容器使用的BeanDefinition,常用的有ClassPathResource和FileSystemResource:
ClassPathResource res = new ClassPathResource("beans.xml");
如果使用FileSystemXmlApplicationContext容器,则源码里使用文件系统去获取资源:
@Override
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}