技术要求:使用配置文件,实现一个简单的AOP框架
技术要点:1、Java的反射
2、工厂模式
3、代理模式
4、JavaBean
配置文件信息:(目标=通知)
#xxx=java.util.ArrayList //这是注释掉
xxx=cn.yang.ProxyFactoryBean
xxx.proxied=java.util.ArrayList
xxx.advice=cn.yang.MyAdvice
//负责创建目标或代理类的实例对象,并通过配置文件实现切换
//传入配置文件
public class BeanFactory{
Properties prop = new Properties();
Object bean = null;
public BeanFactory(InputStream ips){
props.load(ips);
}
public Object getBean(String name){
String className = props.getProperty(name);
Class class = Class.forName(className);
bean = class.newInstance();
if(bean instanceof ProxyFBInterf){
ProxyFBInterf proxyFBean = (ProxyFBInterf)bean;
Advice advice = (Advice)Class.forName(props.getProperty(name+".advice")).newInstance();
Object proxied = (Object)Class.forName(props.getProperty(name+".proxied")).newInstance();
proxyFacotryBean.setAdviec(advice);
proxyFacotryBean.setProxied(proxied);
return proxy = proxyFBean.getProxy();
}
return bean;
}
}
public interface ProxyFBInterf{
public Object getProxy();
}
//代理工厂:用于动态生成代理
//实际应用,这应该是一个接口
public class ProxyFacotryBean implements ProxyFBInterf{
private Advice advice = null;
private Object proxied = null;
public Object getProxy(){
return Proxy.newProxyInstance(
proxied.getClass().getClassLoader(),
proxied.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//....
advice.beforeMethod();
Object retVal = method.invoke(proxiec, args);
advice.afterMethod();
//....
return retVal;
}
});
}
public void setAdvice(Advice advice){
this.advice = advice;
}
public void setProxied(Object proxied){
this.proxied = proxied;
}
}
//main
public class Test{
public static void main(String[] args){
InputStream ips = Test.class.getResource("config.properties");//使用相对路径
Object bean = new BeanFactory(ips).getBean("xxx");
System.out.println(bean.getClass().getName()); //判断是代理,还是被代理类(目标)
}
}
|
|