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());
}
}
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;
}
}
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