spring学习笔记(二) 模拟spring注入_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > spring学习笔记(二) 模拟spring注入

spring学习笔记(二) 模拟spring注入

 2012/1/20 10:05:12  zakaz168  程序员俱乐部  我要评论(0)
  • 摘要:spring学得模模糊糊,许多东西也只是过了一下,其实还是不懂,记下来供以后用的时候能够得到一些帮助吧。beans.xml<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www
  • 标签:笔记 学习 Spring 学习笔记
spring学得模模糊糊,许多东西也只是过了一下,其实还是不懂,记下来供以后用的时候能够得到一些帮助吧。
beans.xml
<?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="personServiceBean" class="com.gentle.service.impl.PersonServiceBean">
		<property name="personDao" ref="personDaoBean" />
	</bean>
	<bean id="personDaoBean" class="com.gentle.dao.impl.PersonDaoBean" />
</beans>

单元测试SpringTest
package junit.test;

import org.junit.Test;

import com.gentle.service.PersonService;
import com.gentle.context.support.GentleClassPathXmlApplicationContext;
import junit.framework.TestCase;

public class SpringTest extends TestCase {
	@Test
	public void test() {
		GentleClassPathXmlApplicationContext context = new GentleClassPathXmlApplicationContext(
				"beans.xml");
		PersonService personService = (PersonService) context.getBean("personServiceBean");
		personService.Save();
	}
}

ClassPathXmlApplicationContext的模拟类GentleClassPathXmlApplicationContext
package com.gentle.context.support;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gentle.context.support.BeanDefinition;

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

public class GentleClassPathXmlApplicationContext {
	private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();
	private Map<String, Object> singletons = new HashMap<String, Object>();

	public GentleClassPathXmlApplicationContext(String fileName) {
		this.readXML(fileName);
		this.instanceBeans();
		this.injectObject();
	}
	/**
	 * 为bean的属性注入值
	 */
	private void injectObject() {
		for(BeanDefinition beanDefinition:beanDefinitions) {//循环所有的bean
			Object bean = singletons.get(beanDefinition.getId());//得到bean
			if(bean!=null) {
				try {
					PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
					for(PropertyDefinition propertyDefinition:beanDefinition.getProperties()) {
						for(PropertyDescriptor propertyDescriptor : ps) {
							if(propertyDefinition.getName().equals(propertyDescriptor.getName())) {
								Method setter = propertyDescriptor.getWriteMethod();//取得属性的setter方法
								if(setter!=null) {
									Object value = singletons.get(propertyDefinition.getRef());
									setter.setAccessible(true);//设置私有方法访问权限
									setter.invoke(bean, value);//把引用对象注入到属性中
								}
								break;
							}
						}
					}
				} catch (IntrospectionException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 实例化容器
	 */
	private void instanceBeans() {
		for(BeanDefinition definition:beanDefinitions) {
			try {
				if(definition.getClassName()!=null && !"".equals(definition.getClassName())) {
					singletons.put(definition.getId(), Class.forName(definition.getClassName()).newInstance());
				}
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 读取XML配置文件
	 * 
	 * @param fileName
	 */
	@SuppressWarnings("unchecked")
	private void readXML(String fileName) {
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			URL xmlPath = this.getClass().getClassLoader()
					.getResource(fileName);// 取得文件
			document = reader.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 className = element.attributeValue("class");// 获取class属性值
				BeanDefinition definition = new BeanDefinition(id, className);
				XPath propertysub = element.createXPath("ns:property");//创建查询路径
				propertysub.setNamespaceURIs(nsMap);//设置命名空间
				List<Element> properties = propertysub.selectNodes(element);//获取property下面所有节点
				for(Element property:properties) {
					String propertyName = property.attributeValue("name");//获取name属性值
					String propertyRef = property.attributeValue("ref");//获取ref属性值
					PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyRef);//实例化对象
					definition.getProperties().add(propertyDefinition);//添加propertyDefinition对象到bean对象
				}
				
				beanDefinitions.add(definition);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

	public Object getBean(String beanName) {
		return singletons.get(beanName);
	}
}

BeanDefinition
package com.gentle.context.support;

import java.util.ArrayList;
import java.util.List;

public class BeanDefinition {
	private String id;
	private String className;
	private List<PropertyDefinition> properties = new ArrayList<PropertyDefinition>();
	
	public List<PropertyDefinition> getProperties() {
		return properties;
	}
	public void setProperties(List<PropertyDefinition> properties) {
		this.properties = properties;
	}
	public BeanDefinition(String id,String className) {
		this.id = id;
		this.setClassName(className);
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getClassName() {
		return className;
	}
	
}

PropertyDefinition
package com.gentle.context.support;

public class PropertyDefinition {
	private String name;
	private String ref;
	
	public PropertyDefinition(String name, String ref) {
		this.name = name;
		this.ref = ref;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRef() {
		return ref;
	}
	public void setRef(String ref) {
		this.ref = ref;
	}
	
}	

PersonDao
package com.gentle.dao;

public interface PersonDao {

	public abstract void save();

}

PersonDaoBean
package com.gentle.dao.impl;

import com.gentle.dao.PersonDao;

public class PersonDaoBean implements PersonDao {
	
	public void save() {
		System.out.println("调用PersonDaoBean中的save()方法");
	}
}

PersonService
package com.gentle.service;


public interface PersonService {
	public abstract void Save();
}

PersonServiceBean
package com.gentle.service.impl;

import com.gentle.dao.PersonDao;
import com.gentle.service.PersonService;

public class PersonServiceBean implements PersonService {

	private PersonDao personDao;
	
	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	@Override
	public void Save() {
		personDao.save();
	}
	
}

发表评论
用户名: 匿名