Spring_使用XML配置文件实现依赖注入


	


	
		
	


package com.bjsxt.spring;

public interface BeanFactory {
	public Object getBean(String name);
}

package com.bjsxt.spring;

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

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class ClassPathXmlApplicationContext implements BeanFactory {
	private Map beans = new HashMap();

	@SuppressWarnings("rawtypes")
	public ClassPathXmlApplicationContext() throws Exception {
		SAXBuilder sb = new SAXBuilder();
		Document document = sb.build(ClassPathXmlApplicationContext.class
				.getClassLoader().getResource("beans.xml"));// 获取文件
		Element root = document.getRootElement();// 获取根元素
		List list = root.getChildren();// 获取名字为bean的所有元素(子元素)
		for (int i = 0; i < list.size(); i++) {
			Element element = (Element) list.get(i);
			String id = element.getAttributeValue("id");// u
			String clazz = element.getAttributeValue("class");// UserDaoImpl
			Object obj = Class.forName(clazz).newInstance();// 生成Class实例UserDaoImpl.class
			System.out.println(id);
			System.out.println(clazz);
			beans.put(id, obj);// 添加至map集合

			for (Element propertyElement : (List) element
					.getChildren("property")) {
				String name = propertyElement.getAttributeValue("name");// userDao
				String bean = propertyElement.getAttributeValue("bean");// u
				Object beanObject = beans.get(bean);// UserDaoImpl instance

				String methodName = "set" + name.substring(0, 1).toUpperCase()
						+ name.substring(1);// setUserDao(set,U,serDao)
				System.out.println("method name = " + methodName);

				Method m = obj.getClass().getMethod(methodName,
						beanObject.getClass().getInterfaces()[0]);
				m.invoke(obj, beanObject);
			}
		}
	}

	@Override
	public Object getBean(String name) {
		return beans.get(name);
	}

}

package com.bjsxt.service;

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

public class UserService {
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void add(User user) {
		this.userDao.save(user);
	}
}

package com.bjsxt.service;

import org.junit.Test;

import com.bjsxt.model.User;
import com.bjsxt.spring.BeanFactory;
import com.bjsxt.spring.ClassPathXmlApplicationContext;

public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {
		BeanFactory factory = new ClassPathXmlApplicationContext();

		UserService service = (UserService) factory.getBean("userService");
		
		User user = new User();
		service.add(user);
	}
}


你可能感兴趣的:(Java,xml-IOC_DI,Spring)