jdk 动态代理与spring 动态代理区别

jdk 动态代理的创建速度比cglib的动态代理创建速度要快8倍左右,但cglib的动态代理性能要比jdk动态代理快10倍以上,所以一般sington bean 用cglib动态代理比较好,而prototype bean 用jdk动态代理会较好


jdk动态代理类:

package com.sharp.cxf.service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 类 名 称: MyInvocationHandler
 * 类 描 述: 
 * 创 建 人: peng.xiao
 * 创建时间: 2013-7-23 下午9:32:45
 *
 * 修 改 人:  peng.xiao
 * 操作时间: 2013-7-23 下午9:32:45
 * 操作原因: 
 * 
 */
public class MyInvocationHandler implements InvocationHandler {

	
	private Object obj;
	
	public MyInvocationHandler(Object obj) {
		super();
		this.obj = obj;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("++++++++++");
		return method.invoke(obj, args);
	}

}

cglib动态代理类:

package com.sharp.cxf.service;

import java.lang.reflect.Method;

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

public class MyMethodIntercetpor implements MethodInterceptor {

	private Enhancer enhancer = new Enhancer();
	
	@SuppressWarnings("unchecked")
	public <T> T getProxy(Class<T> cls){
		enhancer.setSuperclass(cls);
		enhancer.setCallback(this);
		return (T)enhancer.create();
	}
	
	@Override
	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		System.out.println("+++++++++++++++++");
		return proxy.invokeSuper(obj, args);
	}

}

main方法:

package com.sharp.cxf.service;

import java.lang.reflect.Proxy;

import com.sharp.cxf.service.impl.UserServiceImpl;

public class Main {
	public static void main(String[] args) {
		IUserService userService = new UserServiceImpl();
		
		
		/**
		 * java 动态代理
		 */
		/*MyInvocationHandler hander = new MyInvocationHandler(userService);
		IUserService proxy = (IUserService)Proxy.newProxyInstance(userService.getClass().getClassLoader(), 
				userService.getClass().getInterfaces(), hander);*/
		/**
		 * cglib 代理
		 */
		MyMethodIntercetpor methodIntercetpor = new MyMethodIntercetpor();
		IUserService proxy = methodIntercetpor.getProxy(UserServiceImpl.class);
		System.out.println(proxy.sayHi());
	}
}


你可能感兴趣的:(jdk 动态代理与spring 动态代理区别)