工厂模式模拟Spring的bean加载过程

一.前言

   在日常的开发过程,经常使用或碰到的设计模式有代理、工厂、单例、反射模式等等。下面就对工厂模式模拟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、运行结果

四.总结
  此例子是一个比较简单的小例子,但是涉及的知识点比较多,需要了解的知识面要比较广泛一些,这边主要的提供了一种学习的方式。

posted @ 2016-10-09 10:13  独具匠心  阅读(5955)  评论(1编辑  收藏  举报