您的位置:首页 > 编程语言 > Java开发

实现类似于Spring的可配置的AOP框架

2011-12-15 14:57 405 查看
AopFrameworkTest.java

import java.io.InputStream;
import java.util.Collection;

public class AopFrameworkTest {

public static void main(String[] args) {
InputStream is = AopFrameworkTest.class.getResourceAsStream("config.properties");
BeanFactory beanFactory = new BeanFactory(is);
Object obj = beanFactory.getBean("testBean");
System.out.println(obj.getClass().getName());
Collection collection = (Collection)obj;
collection.add("zhuang");
collection.add("alex");
System.out.println(collection.size());

}

}


BeanFactory.java

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {
private Properties prop =new Properties();
public BeanFactory(InputStream is){
try {
this.prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}

public Object getBean(String beanName){
String className = this.prop.getProperty(beanName);
Object beanObj = null;
try {
beanObj = Class.forName(className).newInstance();
Object proxy;
if(beanObj instanceof ProxyFactoryBean){
ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)beanObj;
proxyFactoryBean.setTarget(Class.forName(this.prop.getProperty(beanName+".target")).newInstance());
proxyFactoryBean.setAdvice((MyAdvice)Class.forName(this.prop.getProperty(beanName+".advice")).newInstance());
proxy = proxyFactoryBean.getProxy();
return proxy ;
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return beanObj;
}
}


ProxyFactoryBean.java

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactoryBean {
private Object target ;
private MyAdvice advice ;

public Object getTarget() {
return target;
}

public Object getAdvice() {
return advice;
}

public void setTarget(Object target) {
this.target = target;
}

public void setAdvice(MyAdvice advice) {
this.advice = advice;
}

public Object getProxy(){
Object proxyBean = Proxy.newProxyInstance(this.target.getClass().getClassLoader(),this.target.getClass().getInterfaces(), new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod();
Object obj = method.invoke(target, args);
advice.afterMethod();
return obj;
}
}) ;

return proxyBean;
}
}


Advice.java

public interface Advice {
public void beforeMethod();
public void afterMethod();
}


MyAdvice.java

public class MyAdvice implements Advice{

public void afterMethod() {
System.out.println("after method...");

}

public void beforeMethod() {
System.out.println("before method...");

}

}


config.properties
testBean=javase.aopframework.ProxyFactoryBean
testBean.advice=javase.aopframework.MyAdvice
testBean.target=java.util.ArrayList
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐