引入dom4j jar包
1、新建Person接口和PersonBean
public interface PersonIService { public void helloSpring(); }
public class PersonServiceImpl implements PersonIService { @Override public void helloSpring() { System.out.println("Hello Spring!"); } }
2、在beans.xml中注入PersonBean
<bean id="personIService" class="cn.server.impl.PersonServiceImpl" />
3、新建BeanDefinition 用于存放从beans.xml中获取的beans
public class BeanDefinition { private String id; private String className; public BeanDefinition(){ } public BeanDefinition(String id, String className) { 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; } }
5、新建 OhterClassPathXMLApplicationContext 用于解析beans.xml
public class OhterClassPathXMLApplicationContext { private List<BeanDefinition> list=new ArrayList<BeanDefinition>(); private Map<String,Object> beans=new HashMap<String, Object>(); public OhterClassPathXMLApplicationContext(String fileName){ this.readXML(fileName); this.instanceBeans(); } private void instanceBeans(){ for(BeanDefinition bean : list){ try { // 创建Bean实例,并放到Map中 if(bean.getClassName()!=null && !bean.getClassName().trim().equals("")){ beans.put(bean.getId(), Class.forName(bean.getClassName()).newInstance()); } } catch (Exception e) { e.printStackTrace(); } } } private void readXML(String fileName){ SAXReader saxReader = new SAXReader(); Document doc=null; try{ // JAVA里面对于类进行调用配置资源的文件数据,以this.getClass().getResourceAsStream()来读取比较合适。 // 路径采用相对路径直接可以从工程的path路径去找。 URL xmlpath=this.getClass().getClassLoader().getResource(fileName); doc=saxReader.read(xmlpath); Map<String,String> nsMap=new HashMap<String,String>(); nsMap.put("ns", "http://www.springframework.org/schema/beans"); // 加入命名空间 XPath xsub=doc.createXPath("//ns:beans/ns:bean"); // 创建 beans/bean的查询路径 xsub.setNamespaceURIs(nsMap); // 设置命名空间 List beans=xsub.selectNodes(doc); // 获取文档下的所有bean节点 for(Object node : beans){ Element element=(Element)node; String id=element.attributeValue("id"); String className=element.attributeValue("class"); BeanDefinition bean=new BeanDefinition(id,className); list.add(bean); } }catch(Exception e){ e.printStackTrace(); } } // 通过Id名称,获取Bean public Object getBean(String name){ return beans.get(name); } }
6、测试代码
@Test public void test2() { OhterClassPathXMLApplicationContext otherContext=new OhterClassPathXMLApplicationContext("beans.xml"); PersonIService personIService=(PersonIService)otherContext.getBean("personIService"); personIService.helloSpring(); }