AOP一直感觉很神秘,记得第一看到这个名词,这个是什么东东呀。
文字不写了,直接代码
IBusiness接口类
package com.aop.proxy;
public interface IBusiness {
public void process();
public void process1();
}
Business实现类
package com.aop.proxy;
public class BusinessImpl implements IBusiness {
public void process() {
System.out.println("执行业务");
}
public void process1() {
System.out.println("执行业务1");
}
}
拦截器LogIntercptor 类
package com.aop.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LogInterceptor implements InvocationHandler {
private Object delegate;
public LogInterceptor(Object delegate){
this.delegate=delegate;
}
public Object invoke(Object obj, Method method, Object[] arg2)
throws Throwable {
Object result=null;
try{
System.out.println("Before process:"+method);
//在这里,可以实现对方法访问权限的简单控制
if(method.getName().equals("process1")){
result=method.invoke(delegate, arg2);
}
System.out.println("After process:"+method);
}
catch(Exception e){
System.out.println("发生异常");
}
return result;
}
}
测试用例
package com.aop.proxy;
import junit.framework.TestCase;
import java.lang.reflect.*;
public class TestAOP extends TestCase {
public void testAOP(){
IBusiness obj=new BusinessImpl();
LogInterceptor interceptor=new LogInterceptor(obj);
IBusiness proxy=(IBusiness)Proxy.newProxyInstance(BusinessImpl.class.getClassLoader(),
BusinessImpl.class.getInterfaces(),
interceptor);
proxy.process();
proxy.process1();
}
}
运行 结果:
Before process:public abstract void com.aop.proxy.IBusiness.process()
After process:public abstract void com.aop.proxy.IBusiness.process()
Before process:public abstract void com.aop.proxy.IBusiness.process1()
执行业务1
After process:public abstract void com.aop.proxy.IBusiness.process1()