//无接口类的aop方法实现
package cn.wyz.aop;
import java.lang.reflect.Method;
import cn.wyz.service.impl.PersonServiceBean;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CGlibProxyFactory implements MethodInterceptor{
private Object targetObject;
public Object creatProxyIntacce(Object targetObject){
this.targetObject=targetObject;
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(this.targetObject.getClass());//非final方法
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
PersonServiceBean bean=(PersonServiceBean)this.targetObject;
Object result=null;//环绕通知
if(bean.getUser()!=null){
//......advice()---->前置通知
try {
result=arg3.invoke(this.targetObject, arg2);
//..........afteradvice()------>后置通知
} catch (Exception e) {
//.....exceptionadvice()----->例外通知
e.printStackTrace();
}finally{
//.....finallyadvice()----->最终通知
}
}
return null;
}
}
//接口类的aop方法实现
package cn.wyz.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import cn.wyz.service.impl.PersonServiceBean;
public class JDKProxyFactory implements InvocationHandler {
private Object targetObject;
public Object creatProxyIntacce(Object targetObject){
this.targetObject=targetObject;
return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
this.targetObject.getClass().getInterfaces(), this);
}
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
PersonServiceBean bean=(PersonServiceBean)this.targetObject;
Object result=null;
if(bean.getUser()!=null){
arg1.invoke(this.targetObject, arg2);
}
return result;
}
}
posted on 2009-04-02 22:34
asiawang 阅读(359)
评论(0) 编辑 收藏