(一)模拟spring //实现AOP,模拟Spring /** * BeanFactory * ProxyFactoryBean */ class BeanFactory{ private Properties pro = new Properties(); //加载配置文件 public BeanFactory(InputStream in){ try { pro.load(in); } catch (Exception e) { } } public Object getBean(String name)throws Exception{ Class clazz = Class.forName(pro.getProperty(name)); Object bean = clazz.newInstance(); if(bean instanceof ProxyFactoryBean){ ProxyFactoryBean proxyBean = (ProxyFactoryBean)bean; Advice advice = (Advice) Class.forName(pro.getProperty(name+".advice")).newInstance(); Object target = Class.forName(pro.getProperty(name+".target")).newInstance(); proxyBean.setAdvice(advice); proxyBean.setTar(target); return proxyBean.getProxy(); } return bean; } } class ProxyFactoryBean{ private Object tar; private Advice advice; public Object getTar() { return tar; } public void setTar(Object tar) { this.tar = tar; } public Advice getAdvice() { return advice; } public void setAdvice(Advice advice) { this.advice = advice; } public Object getProxy(){ return Proxy.newProxyInstance( tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), new MyInvocationHandler(tar, advice)); } }
|