自定义spring容器

本文介绍了一种基于Spring框架的自定义容器实现方法,通过解析XML配置文件来注册和实例化Bean,展示了如何使用该容器替代Spring的标准ApplicationContext。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?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="com.icss.service.impl.PersonServiceBean"></bean>

</beans>

=================================

package com.icss.service;

public interface PersonService {

    public abstract void save();

}

================================

package com.icss.service.impl;

import com.icss.service.PersonService;

public class PersonServiceBean implements PersonService {
    @Override
    public void save(){
        System.out.println("我是save()方法");
    }
}


===============================

package junit.test;

public class BeanDefinition {
    private String id;
    private String className;
    public BeanDefinition(String id, String className) {
        super();
        this.id = id;
        this.className = className;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
}

===============================

package junit.test;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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


/**
 * 自定义容器
 * @author Administrator
 *
 */
public class IcssClassPathXMLApplicationContext {
    
    private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();
    private Map<String, Object> sigletons = new HashMap<String, Object>();
    
    public IcssClassPathXMLApplicationContext(String filename){
        this.readXML(filename);
        this.instanceBeans();
    }
    /**
     * 完成bean的实例化
     */
    private void instanceBeans() {
        for(BeanDefinition beanDefinition : beanDefinitions){
            try {
                if(beanDefinition.getClassName() != null && !"".equals(beanDefinition.getClassName().trim()))
                sigletons.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");
            //创建beans/bean查询路径
            XPath xsub = document.createXPath("//ns:beans/ns:bean");
            xsub.setNamespaceURIs(nsMap);//设置命名空间
            List<Element> beans = xsub.selectNodes(document);
            for(Element element : beans){
                String id = element.attributeValue("id");//获取id属性值
                String clazz = element.attributeValue("class");//获取class属性值
                BeanDefinition beanDefine = new BeanDefinition(id, clazz);
                beanDefinitions.add(beanDefine);
            }
        } catch (Exception e) {
            
        }
    }
    /**
     * 获取bean实例
     * @param beanName
     * @return
     */
    public Object getBean(String beanName){
        return this.sigletons.get(beanName);
    }
}

===============================

package junit.test;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.icss.service.PersonService;

public class SpringTest {

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        PersonService personService = (PersonService) ctx.getBean("personService");
        personService.save();
    }

    
    /**
     * 使用自定义容器
     */
    @Test
    public void testInstance() {
        IcssClassPathXMLApplicationContext ctx = new IcssClassPathXMLApplicationContext("beans.xml");
        PersonService personService = (PersonService) ctx.getBean("personService");
        personService.save();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值