模拟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);
	}
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值