测试代码链接:spring-learn
spring的IOC模块主要功能就是管理对象的容器
主要分成两个部分: 1.解析用户的配置信息; 2.创建对象并初始化对象
1.解析用户的配置信息
XML配置 :
<bean id="loginServiceImpl" class="com.china.only.user.service.impl.LoginServiceImpl"></bean>
测试代码 :
public static void testMyBean(){
AbstractApplicationContext aContext = new ClassPathXmlApplicationContext("beans-ioc.xml");
LoginServiceImpl loginService = (LoginServiceImpl) aContext.getBean("loginServiceImpl");
try {
loginService.login(new HashMap<>());
} catch (Exception e) {
e.printStackTrace();
}
}
ClassPathXmlApplicationContext 从类路径中查找*.xml文件(一般为App ClassLoade类加载的加载路径),这个类返回了代表xml文件资源的数据结构: ClassPathContextResource
ClassPathContextResource,这个类其实封装了一个String类型的资源路径名称和类加载器,然后通过调用该类的getInputStream
public InputStream getInputStream() throws IOException {
InputStream is;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else if (this.classLoader != null) {
is = this.classLoader.getResourceAsStream(this.path);
}
else {
is = ClassLoader.getSystemResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
return is;
}
有了xml的InputStream输入流,就可以使用DOM对xml文件进行解析,不熟悉DOM如何解析xml可以自行百度,这个就是Spring框架底层处理xml的方式,由于读取xml实现较为繁琐,我这里使用yaml格式文件代替xml作为框架的配置文件,当然后序可以扩展添加对xml配置文件的支持.
模仿spring的项目: abc
在com.abc.example.Main下的测试代码,读取yaml配置文件:
public static void testYamlAppContext(){
ClassPathYamlAppContext context = new ClassPathYamlAppContext("abc.yaml");
Orange orange = (Orange) context.getBean("orange");
System.out.println(orange.getName());
ChineseLesson chineseLesson = (ChineseLesson) context.getBean("lesson");
chineseLesson.function();
}
在abc项目中只考虑了类路径下的资源文件加载,所以较spring简化了很多,只要简单封装资源路径即可
public void registryBeanDefinition() {
for(String path: pathes){
Resource resource = new ClassPathResource(path);
ParserData data = parserFrom(resource);
registryBeanDefinition(convertToBeanDefinition(data),factory);
}
}
下一篇文章讲解spring具体如何将xml中用户自定义的bean解析为BeanDefinition这样的数据结构.