【練習】spring的簡易實作(一)
在第一部分我們實作讀取xml的配置,然后實體化xml中的bean
首先定義一個xml和相關的class類
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="petStore"
>
</bean>
<bean id="invalidBean"
>
</bean>
</beans>
package org.litespring.service.v1;
public class PetStoreService {
}
我們先把目標寫出來,即測驗用例,就是先把我們想要達到的效果展示出來,然后再一步步的代碼去實作
package org.litespring.test.v1;
import org.junit.Assert;
import org.junit.Test;
import org.litespring.context.ApplicationContext;
import org.litespring.context.support.ClassPathXmlApplicationContext;
import org.litespring.context.support.FileSystemXmlApplicationContext;
import org.litespring.service.v1.PetStoreService;
public class ApplicationContextTest {
@Test
public void testGetBean() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("petstore-v1.xml");
PetStoreService petStore = (PetStoreService)ctx.getBean("petStore");
Assert.assertNotNull(petStore);
}
}
看到這里,我們發現自己只要可以讀取xml(借助dom4j.jar),以及通過反射實體化一個物件那么就可以實作了,按照這個思路,我們可以很容易地實作下面這樣的代碼,
首先定義一個BeanDefinition,它用來存盤xml中的bean定義
public class BeanDefinition {
private String id;
private String className;
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
public String getId() {
return id;
}
public String getClassName() {
return className;
}
}
然后,我們實作主體的邏輯部分
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.*;
public class ClassPathXmlApplicationContext {
private Map<String, BeanDefinition> bds = new HashMap<>();
public ClassPathXmlApplicationContext(String filePath) throws Exception {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
Element root = doc.getRootElement();
Iterator<Element> iter = root.elementIterator();
while(iter.hasNext()){
Element ele = iter.next();
String id = ele.attributeValue("id");
String className = ele.attributeValue("class");
bds.put(id, new BeanDefinition(id, className));
}
}
public Object getBean(String id) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
BeanDefinition bd = bds.get(id);
String className = bd.getClassName();
Class<?> clz = this.getClass().getClassLoader().loadClass(className);
return clz.newInstance();
}
}
然后,我們欣喜的看到測驗用例可以成功,最后,我們反思一下自己寫的代碼,并且和spring的實作對比,會發現,有很多可以重構的地方


我們直接畫一個UML類圖來看吧

代碼實作見:https://github.com/Theone21/mylitespring BeanFactory分支
本文由博客一文多發平臺 OpenWrite 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/107594.html
標籤:其他
上一篇:excel將一個作業表根據條件拆分成多個sheet作業表與合并多個sheet作業表
下一篇:51單片機 知識總結
