本帖最后由 Bule丶 于 2014-8-3 00:19 编辑
BeanFactory:--------------------------
package com.hans.aopframework;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.hans.myproxy.Advice;
public class BeanFactory {
Properties properties = new Properties();
public BeanFactory(InputStream ips){
try {
properties.load(ips);
} catch (IOException e) {
e.printStackTrace();
}
}
public Object getBean(String name){
String className = properties.getProperty(name); //得到类名
Object bean = null;
try {
Class clazzBean = Class.forName(className); //反射得到类
bean = clazzBean.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
if(bean instanceof ProxyBeanFactory){ //如果此类是个代理类
Object proxy = null;
ProxyBeanFactory proxyBeanFactory = (ProxyBeanFactory)bean; //强转代理对象
try {
Advice advice = (Advice) Class.forName(properties.getProperty(name + ".advice")).newInstance(); //得到建议
Object target = Class.forName(properties.getProperty(name + ".target")).newInstance(); //得到目标
proxyBeanFactory.setAdvice(advice);
proxyBeanFactory.setTarget(target);
proxy = proxyBeanFactory.getProxy(); //创建代理
} catch (Exception e) {
e.printStackTrace();
}
}
return bean;
}
}
ProxyBeanFactory:-------------- 负责创建代理
package com.hans.aopframework;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.hans.myproxy.Advice;
public class ProxyBeanFactory {
private static Object target;
private static Advice advice;
public static Object getTarget() {
return target;
}
public static void setTarget(Object target) {
ProxyBeanFactory.target = target;
}
public static Advice getAdvice() {
return advice;
}
public static void setAdvice(Advice advice) {
ProxyBeanFactory.advice = advice;
}
public static Object getProxy() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
advice.content1(method);
Object retObje = method.invoke(target, args);
advice.content2(method);
return retObje;
}
});
}
}
测试类:----------------------
package com.hans.aopframework;
import java.io.InputStream;
public class BeanFactoryTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
InputStream ips = BeanFactoryTest.class.getResourceAsStream("config.properties");
Object f = new BeanFactory(ips).getBean("xxx");
System.out.println(f.getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
晚上看了一晚上,都看完了
|
|