Spring学习笔记——Sprin管理Bean的原理

当我们使用Spring时候在Xml文件中通过

<bean id="service" class="com.finance.service.AmountServiceImpl" />

配置就可以操作该Bean的属性和方法,那么Spring到底是如何实现的呢?下面让我们自己实现这个过程。
首先我模拟Spring的命名方式创建一个Bean管理类MyClassPathXMLApplicationContext.java,代码如下:

// 自定义容器
public class MyClassPathXMLApplicationContext {
    private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
    private Map<String, Object> singletons = new HashMap<String, Object>();

    public MyClassPathXMLApplicationContext(String filename){
                // 1、读取配置文件
        this.readXML(filename);
                // 2、实例化Bean
        this.instanceBeans();
    }
    /**
     * 完成bean的实例化
     */
    private void instanceBeans() {
        for(BeanDefinition beanDefinition : beanDefines){
            try {
                if(beanDefinition.getClassName()!=null && !"".equals(beanDefinition.getClassName().trim()))
                    singletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    /**
     * 读取xml配置文件
     * @param filename
     */
    private void readXML(String filename) {
           SAXReader saxReader = new SAXReader();   
            Document document=null;   
            try{
             URL xmlpath = this.getClass().getClassLoader().getResource(filename);
             document = saxReader.read(xmlpath);
             Map<String,String> nsMap = new HashMap<String,String>();
             nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
             XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
             xsub.setNamespaceURIs(nsMap);//设置命名空间
             List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点 
             for(Element element: beans){
                String id = element.attributeValue("id");//获取id属性值
                String clazz = element.attributeValue("class"); //获取class属性值        
                BeanDefinition beanDefine = new BeanDefinition(id, clazz);
                beanDefines.add(beanDefine);
             }   
            }catch(Exception e){   
                e.printStackTrace();
            }
    }
    /**
     * 获取bean实例
     * @param beanName
     * @return
     */
    public Object getBean(String beanName){
        return this.si呢gletons.get(beanName);
    }
}

配置文件如下:

<?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-2.5.xsd">
          <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>

下面我们来测试一下:

public class SpringTest {
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }
    @Test public void instanceSpring(){
        MyClassPathXMLApplicationContext ctx = new MyClassPathXMLApplicationContext("beans.xml");
        PersonService personService = (PersonService)ctx.getBean("personService");
        personService.save();
    }
}

运行成功

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值