黑马程序员技术交流社区
标题: java基础之--代理模拟Spring [打印本页]
作者: 周发建 时间: 2016-4-1 09:51
标题: java基础之--代理模拟Spring
(一)模拟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));
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |