模拟spring,自定义容器一(属性注入、Bean的实例化)

来源:互联网 发布:nerf淘宝 编辑:程序博客网 时间:2024/05/29 02:37

1. 创建自定义的容器类

package cn.hq.customspring;import java.beans.Introspector;import java.beans.PropertyDescriptor;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 org.apache.commons.beanutils.ConvertUtils;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.XPath;import org.dom4j.io.SAXReader;/** * 自定义的spring容器 * */public class HqClasspathXmlApplicationContext {private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();private Map<String,Object> singletons = new HashMap<String,Object>();public HqClasspathXmlApplicationContext(String filename) {this.readXML(filename);this.instanceBeans();this.injectObject();}//为bean对象的属性注入值private void injectObject() {for(BeanDefinition beanDefinition : beanDefinitions) {Object bean = singletons.get(beanDefinition.getId());if(bean!=null) {try {PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();for(PropertyDefinition propertyDefinition : beanDefinition.getPropertys()) {for(PropertyDescriptor propertyDescriptor : ps) {if(propertyDefinition.getName().equals(propertyDescriptor.getName())) {Method setter = propertyDescriptor.getWriteMethod(); //获取属性的set方法if(setter != null) {Object value = null;if(propertyDefinition.getRef()!=null&&!"".equals(propertyDefinition.getRef().trim())) {value = singletons.get(propertyDefinition.getRef());}else {value = ConvertUtils.convert(propertyDefinition.getValue(), propertyDescriptor.getPropertyType());}setter.setAccessible(true); // 设置为true 以防属性为privatesetter.invoke(bean, value); //将引用对象注入到属性}}}}} catch (Exception e) {e.printStackTrace();}}}}//完成Bean实例化private void instanceBeans() {for(BeanDefinition beanDefinition : beanDefinitions) {try {if(beanDefinition.getClassName() != null && !"".equals(beanDefinition.getClassName().trim())) {singletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());}} catch (Exception e) {e.printStackTrace();} }}//读取XML文件中的bean  @SuppressWarnings("unchecked")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 xPath = document.createXPath("//ns:beans/ns:bean"); //创建beans和bean查询路劲xPath.setNamespaceURIs(nsMap); //设置命名空间List<Element> beans = xPath.selectNodes(document); //获取文档下所有的bean节点for(Element element:beans) {String id = element.attributeValue("id");String clazz = element.attributeValue("class");BeanDefinition beanDefinition = new BeanDefinition(id,clazz);//读取bean的属性property节点XPath xPathProperty = element.createXPath("ns:property"); //xPathProperty.setNamespaceURIs(nsMap); //设置命名空间List<Element> propertys = xPathProperty.selectNodes(element);for(Element property : propertys) {String propertyName = property.attributeValue("name");String propertyRef = property.attributeValue("ref");String propertyValue = property.attributeValue("value");//System.out.println("name=" + propertyName + "-----ref=" + propertyRef);PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyRef,propertyValue);beanDefinition.getPropertys().add(propertyDefinition);}beanDefinitions.add(beanDefinition);}} catch (Exception e) {e.printStackTrace();}}/** * 获取bean实例 * @param beanName * @return */public Object getBean(String beanName) {return singletons.get(beanName);}}


2. 创建自定义的BeanDefinition类

package cn.hq.customspring;import java.util.ArrayList;import java.util.List;public class BeanDefinition {private String id;private String className;private List<PropertyDefinition> propertys = new ArrayList<PropertyDefinition>();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;}public List<PropertyDefinition> getPropertys() {return propertys;}public void setPropertys(List<PropertyDefinition> propertys) {this.propertys = propertys;}}


3. 创建自定义的PropertyDefinition类

package cn.hq.customspring;public class PropertyDefinition {private String name;private String ref;private String value;public PropertyDefinition(String name,String ref,String value) {this.name = name;this.ref = ref;this.value = value;}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;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}}

4. 创建spring的配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here --><!-- 使用scope设置bean对象的实例化作用域(singleton单实例  prototype多实例) --><!-- <bean id="studentService" class="cn.hq.service.impl.StudentServiceImpl" scope="prototype"></bean> --><!-- 使用lazy-init="true"设置bean延迟实例化 --><!-- <bean id="studentService" class="cn.hq.service.impl.StudentServiceImpl"></bean> --><!-- bean的生命周期 --><!-- <bean id="studentService" class="cn.hq.service.impl.StudentServiceImpl" init-method="init"destroy-method="destroy"></bean> --><!-- 通过工厂静态方法实例化对象 --><!-- <bean id="studentService2" class="cn.hq.spring.StudentServiceFactory" factory-method="createStudentBean"></bean> --><!-- 通过工厂类实例化对象 --><!-- <bean id="studentServiceFactory" class="cn.hq.spring.StudentServiceFactory" ></bean><bean id="studentService3" factory-bean="studentServiceFactory" factory-method="createStudentBean2"></bean> --> <bean id="studentDao" class="cn.hq.dao.impl.StudentDaoImpl"></bean><bean id="studentService" class="cn.hq.service.impl.StudentServiceImpl"><property name="studentDao" ref="studentDao"></property><property name="studentName" value="zzhua"></property><property name="studentAge" value="122"></property><property name="salary" value="122.98898"></property></bean></beans>
5.通过容器实例化对象

HqClasspathXmlApplicationContext hqApplicationContext = new HqClasspathXmlApplicationContext("beans.xml");StudentService studentService = (StudentService)hqApplicationContext.getBean("studentService");try {studentService.save();} catch (Exception e) {e.printStackTrace();}



使用的jar包下载地址:

http://download.csdn.net/download/u010879420/10012282



原创粉丝点击