工厂模式模拟Spring Bean的创建过程

一、Spring创建bean原理:

      在以前的Spring项目中,我们都会在xml中配置bean信息,比如id和类名。其实原理就是通过读取xml信息,对应生成相应的bean,并将bean放入缓存,以便快速访问使用。后来以注解的方式配置bean,其实原理都是差不多,通过反射去读取注解的信息,从而实例化类。

二、代码实例:

/**
 * Car
 */
public class Car {
    
    public void run() {
        System.out.println("Car run..");
    }
}

 BeanFactory :

public interface BeanFactory {
    
    Object getBean(String id) throws ExecutionException;

}

BeanFactory 实现类 

/**
 * BeanFactory实现类
 */
public class ClassPathXmlApplicationContext implements BeanFactory {
    
    private Map<String, Object> map = new HashMap<String, Object>();
    
    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);
    }

}

application.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="car" class="com.spring.stu.Car">
    </bean>
</beans>

测试类:

public class BeanFactoryTest {
    
    public static void main(String[] args) throws InstantiationException,
      IllegalAccessException, ClassNotFoundException
      , DocumentException, ExecutionException {
        
        BeanFactory beanFactory = 
        new ClassPathXmlApplicationContext("com/spring/application.xml");
        Object obj = beanFactory.getBean("car");
        Car car = (Car)obj;
        car.run();
    }

}

 

 

 

 

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值