der classLoader = Thread.currentThread().getContextClassLoader(); InputStream ins = classLoader.getResourceAsStream(xml); // 读取指定的配置文件 Document doc = reader.read(ins); Element root = doc.getRootElement(); AopHandler aopHandler = new AopHandler(); // 创建AOP处理器(动态生成的proxy类中持有了aopHandle的引用) for (Iterator iter = root.elementIterator(bean); iter.hasNext();) { // 遍历bean Element element = (Element) iter.next(); Attribute id = element.attribute(id); // 获取bean的属性id、class、aopClass、aopType Attribute cls = element.attribute(class); Attribute aopClass = element.attribute(aopClass); Attribute aopType = element.attribute(aopType); if (aopClass != null && aopType != null) { // 如果配置了aopClass和aopType属性时,需进行拦截操作 Class advisorClass = Class.forName(aopClass.getText()); // 根据aopClass字符串获取对应的类 Advisor advisor = (Advisor) advisorClass.newInstance(); // 创建该类的对象 if (before.equals(aopType.getText())) { // 根据aopType的类型来设置前置或后置顾问 aopHandler.setBeforeAdvisor(advisor); } else if (after.equals(aopType.getText())) { aopHandler.setAfterAdvisor(advisor); } } Class clazz = Class.forName(cls.getText()); // 利用Java反射机制,通过class的名称获取Class对象 Object obj = clazz.newInstance(); // 创建一个对象 Object proxy = (Object) aopHandler.setObject(obj); // 产生代理对象proxy beansMap.put(id.getText(), proxy); // 将对象放入beansMap中,其中id为key,对象为value } } catch (Exception e) { System.out.println(e.toString()); } } /** * 通过bean的id获取bean的对象. * @param beanName bean的id * @return 返回对应对象 */ public Object getBean(String beanName) { Object obj = beansMap.get(beanName); return obj; } }
⑧ 配置文件beans.xml
⑨ 测试类
import com.zdp.service.BusinessService;
import com.zdp.spring.BeanFactory;
/**
* 测试类
* @author zhangjim
*/
public class Client {
public static void main(String[] args) {
BeanFactory beanFactory = new BeanFactory();
beanFactory.init(beans.xml);
BusinessService proxy = (BusinessService) beanFactory.getBean(businessService);
proxy.process();
}
}
三、小结
上文仅仅是简单地模拟了spring的AOP的实现,但还是很好地展现了JDK反射和动态代理在spring中的应用,对于初学者理解AOP应该会有一点帮助。
源码下载地址: http://download.csdn.net/detail/zdp072/7284987
参考资料:http://www.ibm.com/developerworks/cn/java/j-lo-springaopcglib/