自定义spring控制反转及简单原理

首先非常感谢传智播客的spring视频,本文章通过视频的学习才能写出。

所有的源码和所使用的jar包我已经上传到csdn的资源上:http://download.csdn.net/detail/bq1073100909/8056685

源码如下:

首先新建一个java项目:


测试用的Dao和service接口和实现类如下:

PersonDao.java

package org.test.dao;

public interface PersonDao {
	public void add();
}

PersonDaoImpl.java

package org.test.dao.impl;

import org.test.dao.PersonDao;

public class PersonDaoImpl implements PersonDao {

	@Override
	public void add() {
		System.out.println("执行了PersonDaoImpl的add()方法");
	}

}

PersonService.java

package org.test.service;

public interface PersonService {
	public void add();
}

PersonServiceImpl.java

package org.test.service.impl;

import org.test.dao.PersonDao;
import org.test.service.PersonService;

public class PersonServiceImpl implements PersonService {
	private PersonDao personDao;
	
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}


	@Override
	public void add() {
		personDao.add();
	}

}

applicationContext.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="personDao" class="org.test.dao.impl.PersonDaoImpl"></bean>
    <bean id="personService" class="org.test.service.impl.PersonServiceImpl">
    	<property name="personDao" ref="personDao"/>
    </bean>      	
      	
</beans>

BeanDefinition.java 自定义bean的封装类:

package org.junit;

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 List<PropertyDefinition> getPropertys() {
		return propertys;
	}

	public void setPropertys(List<PropertyDefinition> propertys) {
		this.propertys = propertys;
	}

	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;
	}
}
PropertyDefinition.java 自定义属性的封装类:

package org.junit;

/**
 * 自定义属性
 * @author dyb
 *
 */
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;
	}
}

重要的部分来啦:MyClassPathXMLApplicationContext.java

package org.junit;

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;

/**
 * 自定义容器
 * @author dyb
 *
 */
public class MyClassPathXMLApplicationContext {
	private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
	private Map<String, Object> sigletons = new HashMap<String, Object>();
	
	public MyClassPathXMLApplicationContext(String filename) {
		this.readXML(filename);
		this.instanceBeans();
		this.injectObject();
	}
	
	/**
	 * 为bean对象的属性注入值
	 */
	private void injectObject() {
		for(BeanDefinition beanDefinition : beanDefines){
			Object bean = sigletons.get(beanDefinition.getId());
			if(bean!=null){
				try {
					PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
					for(PropertyDefinition propertyDefinition : beanDefinition.getPropertys()){
						for(PropertyDescriptor properdesc : ps){
							if(propertyDefinition.getName().equals(properdesc.getName())){
								Method setter = properdesc.getWriteMethod();//获取属性的setter方法 ,private
								if(setter!=null){
									Object value = null;
									if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){
										value = sigletons.get(propertyDefinition.getRef());
									}else{
										value = ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
									}
									setter.setAccessible(true);
									setter.invoke(bean, value);//把引用对象注入到属性
								}
								break;
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}
	}
	/**
	 * 完成bean的实例化
	 */
	private void instanceBeans() {
		for(BeanDefinition beanDefinition : beanDefines){
			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");//加入命名空间
			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 clazz = element.attributeValue("class"); //获取class属性值     
				BeanDefinition beanDefine = new BeanDefinition(id, clazz);
				XPath propertysub =  element.createXPath("ns:property");
				propertysub.setNamespaceURIs(nsMap);//设置命名空间
				List<Element> propertys = propertysub.selectNodes(element);
				for(Element property : propertys){	 
					String propertyName = property.attributeValue("name");
					String propertyref = property.attributeValue("ref");
					String propertyvalue = property.attributeValue("value");
					PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyref,propertyvalue);
	            	beanDefine.getPropertys().add(propertyDefinition);
				}
				beanDefines.add(beanDefine);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取bean实例
	 * @param beanName
	 * @return
	 */
	public Object getBean(String beanName) {
		return this.sigletons.get(beanName);
	}
	
}
单元测试文件:SpringTest.java

package org.junit;

import org.test.service.PersonService;

public class SpringTest {

	@Test
	public void test() {
		MyClassPathXMLApplicationContext ma = new MyClassPathXMLApplicationContext("applicationContext.xml");
		PersonService personService = (PersonService)ma.getBean("personService");
		personService.add();
	}

}

运行junit后结果如下:

中间出现的问题:

当时我运行时候junit出现error,检查好久才知道是我的jar包导入不全,当时我只导入了dom4j一个jar包。等我把dom4j所有的jar包都导入后就解决了问题。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值