java-web 网上商城实战2 - 解耦合

解耦合

在Utils包中添加一个BeanFactory类的工厂类,创建一个getBean(String className)的方法

根据className到xml配置文件中获得对应的类的完整类名

再通过反射获取一个新的实例返回给调用者

需要用到的jar包

xml解析包与xpath

原理图

bean.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans>

	<bean id="CategoryDAO" class="com.store.dao.impl.CategoryDAOImpl"></bean>
	<bean id="ProductDAO" class="com.store.dao.impl.ProductDAOImpl"></bean>
	<bean id="UserDAO" class="com.store.dao.impl.UserDAOImpl"></bean>
	
	<bean id="CategoryService" class="com.store.service.impl.CategoryServiceImpl"></bean>
	<bean id="ProductService" class="com.store.service.impl.ProductServiceImpl"></bean>
	<bean id="UserService" class="com.store.service.impl.UserServiceImpl"></bean>
	
</beans>

BeanFactory.class

package utils;

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

public class BeanFactory {
	
	public static Object getBean(String id) {
		
		//通过id从bean.xml中查找对应的class
		
		try {
			
			SAXReader saxReader = new SAXReader();
			//获取document对象	
			Document document = saxReader.read(BeanFactory.class.getClassLoader().getResourceAsStream("bean.xml"));
			//获取指定的bean对象 xpath
			Element ele  = (Element) document.selectSingleNode("//bean[@id='"+id+"']");
			//获取bean对象的class属性的值
			String className = ele.attributeValue("class");
			//返回一个通过反射获得的实例
			return Class.forName(className).newInstance();
		} catch (Exception e) {
			System.out.println("输入的bean不存在。");
			e.printStackTrace();
		}
		
		return null;
	}
}

调用

ProductService ps = (ProductService) BeanFactory.getBean("ProductService");

猜你喜欢

转载自blog.csdn.net/alexzt/article/details/81185216