一.前言
在日常的開發過程,經常使用或碰到的設計模式有代理、工廠、單例、反射模式等等。下面就對工廠模式模擬spring的bean加載過程進行解析,如果對工廠模式不熟悉的,具體可以先去學習一下工廠模式的概念。在來閱讀此篇博文,效果會比較好。
二.知識儲備
在介紹本文的之前,不了解或不知道如何解析XML的,請先去學習一下XML的解析。掌握目前主要的幾種解析XML中的一種即可,以下博文說明了如何采用Dom4J解析XML文件的,接下去的例子也是常用Dom4J來解析XML。博文地址參考:http://www.cnblogs.com/hongwz/p/5514786.html;
學習應該是學習一種方式,而不是學習某一種知識點,掌握了學習的方式,以后在開發中,遇到問題我們就可以快速的解決,快速的學習某一方面不了解的知識點,下面提供幾點建議:
1.多閱讀源代碼,多看一些別人的代碼,開卷是有益的。
2.在學習某一項新技術的時候,首先先去下載其對應API進行學習。
3.遇到問題先思考在去google,總有不一樣的體會。
三.例子解析
1、創建對應不同的實例
/** * 汽車類. */ public class Car { public void run() { System.out.println("這是一輛汽車..."); } }
/** * 火車類. */ public class Train { public void run() { System.out.println("這是一輛火車...."); } }
2、創建BeanFactory
public interface BeanFactory { Object getBean(String id) throws ExecutionException; }
/** * BeanFactory實現類 */ public class ClassPathXmlApplicationContext implements BeanFactory { private Map<String, Object> map = new HashMap<String, Object>(); @SuppressWarnings("unchecked") public ClassPathXmlApplicationContext(String fileName) throws DocumentException, InstantiationException, IllegalAccessException, ClassNotFoundException { //加載配置文件 SAXReader reader = new SAXReader(); Document document = reader.read(ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(fileName)); //獲取根節點 Element root = document.getRootElement(); //獲取子節點 List<Element> childElements = root.elements(); for (Element element : childElements) { map.put(element.attributeValue("id"), Class.forName(element.attributeValue("class")).newInstance()); } } @Override public Object getBean(String id) throws ExecutionException { return map.get(id); } }
3、applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="car" class="com.shine.spring.domain.Car"> </bean> <bean id="train" class="com.shine.spring.domain.Train"> </bean> </beans>
4、測試類
public class BeanFactoryTest { public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, DocumentException, ExecutionException { BeanFactory beanFactory = new ClassPathXmlApplicationContext("com/shine/spring/applicationContext.xml"); Object obj = beanFactory.getBean("car"); Car car = (Car)obj; car.run(); } }
5、運行結果
四.總結
此例子是一個比較簡單的小例子,但是涉及的知識點比較多,需要了解的知識面要比較廣泛一些,這邊主要的提供了一種學習的方式。