Spring之BeanFactory(模拟ioc的反射实现)

 spring的IOC容器能够帮我们自动new对象,对象交给spring管之后我们不用自己手动去new对象了。那么它的原理是什么呢?是怎么实现的呢?下面我来简单的模拟一下spring的机制,相信看完之后就会对spring的原理有一定的了解。

  spring使用BeanFactory来实例化、配置和管理对象,但是它只是一个接口,里面有一个getBean()方法。我们一般都不直接用BeanFactory,而是用它的实现类ApplicationContext,这个类会自动解析我们配置的applicationContext.xml,然后根据我们配置的bean来new对象,将new好的对象放进一个Map中,键就是我们bean的id,值就是new的对象。

首先我们建立一个BeanFactory接

 package com.spring; 
 public interface BeanFactory {
     Object getBean(String id);}

}

然后建立一个BeanFactory的实现类ClassPathXmlApplicationContext.java

package com.spring;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class ClassPathXmlApplicationContext implements BeanFactory {
    private Map<String, Object> beans = new HashMap<String, Object>();
    public ClassPathXmlApplicationContext(String fileName) throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream(fileName));
        List<Element> elements = document.selectNodes("/beans/bean");
        for (Element e : elements) {
            String id = e.attributeValue("id");
            String value = e.attributeValue("class");
            Object o = Class.forName(value).newInstance();
            beans.put(id, o);
        }
    }
    
    public Object getBean(String id) {
        return beans.get(id);
    }

}

后配置applicationContext.xml


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

建类的时候顺便演示一下工厂模式,其实BeanFactory它也是一种工厂模式的


package com.spring;

 public interface Moveable {
     void run();
 }

Car类


package com.spring;

public class Car implements Moveable{
    
    public void run(){
        System.out.println("拖着四个轮子满街跑car·····");
    }
}

Plane类 

package com.spring;

public class Plane implements Moveable{

    public void run() {
        System.out.println("拖着翅膀天空飞plane......");
    }
    
}

试效果


package com.spring;

import org.dom4j.DocumentException;

public class Test {
    public static void main(String[] args) throws Exception {
        BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        Object o = factory.getBean("c");
        Moveable m = (Moveable)o;
        m.run();
    }

}

由于Map容器里面保存的是Object类型,所以通过getBean()方法取出来的对象要强制类型转换。

转载于:https://my.oschina.net/freer/blog/897915

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值