模拟Spring的IOC

基于上次简单的模拟spring有重新写了个模拟spring的IOC的程序:

package com.gd.model;
/**
 * 
 * @author sandy
 *
 */
public class User {
	private String username;
	private String password;
	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}
	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

}

 

package com.gd.dao;

import com.gd.model.User;

/**
 * 
 * @author sandy
 *
 */
public interface UserDao {
	void addUser(User user);
}

 

/**
 * 
 */
package com.gd.dao.impl;

import com.gd.dao.UserDao;
import com.gd.model.User;

/**
 * @author sandy
 *
 */
public class UserDaoImpl implements UserDao {
	public void addUser(User user) {
		System.out.println("添加用户名称为:"+user.getUsername()+"的用户成功!");
	}
}

 

package com.gd.service;

import com.gd.model.User;

/**
 * 
 * @author sandy
 *
 */
public interface UserService{
	void addUser(User user);
}

 

/**
 * 
 */
package com.gd.dao.service.impl;

import com.gd.dao.UserDao;
import com.gd.model.User;
import com.gd.service.UserService;

/**
 * @author sandy
 *
 */
public class UserServiceImpl implements UserService {

	UserDao  userDao;
	public void addUser(User user) {
		this.userDao.addUser(user);
	}
	/**
	 * @param userDao the userDao to set
	 */
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}

 

/**
 * 
 */
package com.gd.spring;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

/**
 * @author sandy
 * 从classpath环境配置读取配置文件 该类实现了Bean工厂接口
 */
public class ClasspathXmlApplicationContext implements BeanFactory {

	//定义一个存放bean信息的容器
	private Map<String, Object> container = new HashMap<String, Object>();

	//把传进来fileName文件用dom4j的方式解析,把解析后的结果放到容器container中
	@SuppressWarnings("unchecked")
	public ClasspathXmlApplicationContext(String fileName)
			throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, InvocationTargetException {
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(this.getClass().getClassLoader()
					.getResourceAsStream(fileName));
			Node root = document.selectSingleNode("/beans");
			List list = root.selectNodes("bean");
			for (Object object : list) {
				Element element = (Element) object;
				String beanId = element.attributeValue("id");
				Object clazz = Class.forName(element.attributeValue("class"))
						.newInstance();
				container.put(beanId, clazz);
				Iterator<Element> iter = element.elementIterator();
				while (iter.hasNext()) {
					Element propertyElement = iter.next();
					//获取property中的name="userDao"的值
					String name = propertyElement.attributeValue("name");
					//获取property中的bean="udao"的值
					String bean = propertyElement.attributeValue("bean");
					//获取bean="udao"的bean对象
					Object beanObject = container.get(bean);
					//拼装setUserDao方法				   
					String methodName = "set"
							+ name.substring(0, 1).toUpperCase()
							+ name.substring(1);
					System.out.println(methodName);
					//通过反射方式获取setUserDao方法
					Method method = clazz.getClass().getMethod(methodName,
							beanObject.getClass().getInterfaces()[0]);
					//调用service的setUserDao方法
					method.invoke(clazz, beanObject);
				}
			}
		} catch (DocumentException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	//根据beanId来从容器中获得bean的实例
	public Object getBean(String beanId) {
		return container.get(beanId);
	}
}

 

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="udao" class="com.gd.dao.impl.UserDaoImpl"></bean>
	<bean id="userService" class="com.gd.dao.service.impl.UserServiceImpl">
		<property name="userDao" bean="udao"/>
	</bean>
</beans>

 客户端测试代码:

package com.gd.service;

import java.lang.reflect.InvocationTargetException;

import org.junit.Test;

import com.gd.model.User;
import com.gd.spring.BeanFactory;
import com.gd.spring.ClasspathXmlApplicationContext;

/**
 * 
 * @author sandy
 * 
 */
public class TestUserService {

	@Test
	public void addUser() throws SecurityException, IllegalArgumentException,
			NoSuchMethodException, InvocationTargetException {
		User u = new User();
		u.setUsername("lgd");
		BeanFactory factory = new ClasspathXmlApplicationContext(
				"applicationContext.xml");
		UserService service = (UserService) factory.getBean("userService");
		service.addUser(u);
	}
}

 

 

你可能感兴趣的:(DAO,spring,bean,JUnit,IOC)