实现Spring无顺序加载所有bean

http://www.gwdang.com

http://www.gwdang.com/app/extension

 

实现Spring无顺序加载所有bean:

 

配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans>

<bean id="user" class="cn.myc.bean.User">

<property name="name" value="Jack"/>

<property name="age" value="88"/>

<property name="addr" ref="addr"></property>

</bean>

<bean id="addr" class="cn.myc.bean.Addr">

<property name="city" value="中国北京"/>

<property name="zip" value="100085"/>

<property name="zipCode" ref="zip"/>

</bean>

<bean id="zip" class="cn.cmy.bean.Zip">

<property name="zip" value="10008888888"/>

<property name="code" value="999999"></property>

</bean>

</beans>

加载上面的类如下:

package cn.myc.bean;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

public class ObjectFactory {

public ObjectFactory() throws Exception {

SAXReader r = new SAXReader();

final Document dom = r.read(ObjectFactory.class.getResourceAsStream("beans.xml"));

class Load{

//使用递归实现二层关系bean的加载

public void load(String xpath) throws Exception{

List<Element> beans = dom.selectNodes(xpath);

for(Element e:beans){

String key = e.attributeValue("id");

Object bean = null;

if(!map.containsKey(key)){//判断是否已经加载这个bean如果已经加载则不再重复加载

String className = e.attributeValue("class");

bean = Class.forName(className).newInstance();

map.put(key,bean);

//遍历所有属性

List<Element> props = e.elements("property");

for(Element p : props){

String name = p.attributeValue("name");

Object value = p.attributeValue("value");

if(value==null){

value = p.attributeValue("ref");

load("//bean[@id='"+value+"']");

//再从集合中获取bean

value = getBean(""+value);

}

BeanUtils.setProperty(bean,name,value);

}

}

}

}

};

//用内部类的递归实现对所有bean只加载一次

new Load().load("//bean");

System.err.println(">>"+map);

}

//声明容器

private Map<String,Object> map = new HashMap<String, Object>();

//获取bean的方法

public Object getBean(String id){

return map.get(id); 

}

public static void main(String[] args) throws Exception {

new ObjectFactory();

}

}

 

你可能感兴趣的:(实现Spring无顺序加载所有bean)