JDK动态代理和cglib代理对比

1.JDK动态代理:所要代理的类必须实现了接口。

 

public class JDKProxyFactory implements InvocationHandler{
	private Object targetObject;
	
	public Object createProxyIntance(Object targetObject){
		this.targetObject = targetObject;
		return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(), 
				this.targetObject.getClass().getInterfaces(), this);
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {//环绕通知
		PersonServiceBean bean = (PersonServiceBean) this.targetObject;
		Object result = null; 
		if(bean.getUser()!=null){
			//..... advice()-->前置通知
			try {
				result = method.invoke(targetObject, args);
				// afteradvice() -->后置通知
			} catch (RuntimeException e) {
				//exceptionadvice()--> 例外通知
			}finally{
				//finallyadvice(); -->最终通知
			}
		}

		return result;
	}

}

 使用是:

 

                JDKProxyFactory factory = new JDKProxyFactory();
		PersonService service = (PersonService) factory.createProxyIntance(new PersonServiceBean("xxx"));
		service.save("888");

 

2。cglib可实现没有接口的类的代理:

 

package com.fsj.proxy;

import java.lang.reflect.Method;

import com.fsj.service.PersonService;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;


public class CGLIBProxy implements MethodInterceptor{

	private Object targetObject;
	
	public Object createProxyInstance(Object targetObject)
	{
		this.targetObject = targetObject;
		Enhancer enhancer = new Enhancer();//使用cglib的Enhancer		
		//将目标对象的类设置为enhancer的父类,
		//那么enhancer会覆盖目标类中的所有非final的方法,在覆盖方法中加入一些自身的代码
		enhancer.setSuperclass(this.targetObject.getClass());
		//回调自身,前提是必须实现MethodInterceptor接口
		enhancer.setCallback( this);//会回调intercept方法
		//返回代理对象
		return enhancer.create();
	}

	/**
	 * @param proxy 代理对象本身
	 * @param method 拦截到的方法
	 * @param args 方法的所有参数
	 * @param methodProxy 方法的代理对象
	 */
	@Override
	public Object intercept(Object proxy, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
		//调用前处理------------advice()------前置通知
		PersonService ps = (PersonService)this.targetObject;
		Object result = null;
		if(ps.getName()!=null)
		{
			
			try {
				result = methodProxy.invoke(targetObject, args);
				//调用后也可以处理------------afteradvice()--------后置通知
			} catch (Exception e) {
				//出错时处理------------exceptionadvice()---------例外通知
				e.printStackTrace();
			}finally
			{
				//出不出错都处理------------finallyadvice()--------最终通知
			}
		}
		
		return result;
	}
}

 

 

使用是:

 

		PersonService ps = new PersonService();
//		ps.setName("fs");		
		CGLIBProxy cglibProxy = new CGLIBProxy();
		PersonService  psProxy = (PersonService)cglibProxy.createProxyInstance(ps);
		psProxy.add();

 

 

 

你可能感兴趣的:(jdk,bean,.net)