Java——cglib代理与jdk动态代理

动态代理的作用:在不修改代码下,可以使用动态代理对方法进行增强,可以在方法执行前后进行如日志等操作。

先看代码:

jdk动态代理:

package cn.edu.uest;
	public interface UserService {
		public String getName(String name);
		public String getAge(int age);
	}


package cn.edu.uest;

public class UserServiceImpl implements UserService {

	@Override
	public String getName(String name) {
		 System.out.println("------getName------");  
	        return "Tom";  
	}

	@Override
	public String getAge(int age) {
		System.out.println("------getAge------");  
        return "10";  
	}
	
}


package cn.edu.uest;


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


public class jdk_invocationHandler implements InvocationHandler{


	private Object obj;
	
	jdk_invocationHandler(Object obj){
		super();
		this.obj=obj;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("before"+method.getName());
		Object bb=method.invoke(obj, args);
		System.out.println("after"+method.getName());
		return bb;
	}
	
}


cglib动态代理:

package cn.edu.uest;


import java.lang.reflect.Method;


import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;


public class cglib_Invocation implements MethodInterceptor{


	@Override
	public Object intercept(Object paramObject, Method paramMethod,
			Object[] paramArrayOfObject, MethodProxy paramMethodProxy)
			throws Throwable {
		System.out.println("before"+paramMethodProxy.getSuperName());
		Object bb=paramMethodProxy.invokeSuper(paramObject, paramArrayOfObject);
		System.out.println("after"+paramMethodProxy.getSuperName());
		return bb;
	}


}

main方法:

package cn.edu.uest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.springframework.cglib.proxy.Enhancer;

public class Test {

	public static void main(String[] args) {
		//jdk
//		UserService us=new UserServiceImpl();
//		InvocationHandler ih=new jdk_invocationHandler(us);
//		UserService ss=(UserService)Proxy.newProxyInstance(us.getClass().getClassLoader(),
//				us.getClass().getInterfaces(), ih);
//		System.out.println(ss.getName("张三"));
//		System.out.println(ss.getAge(20));
		//cglib
		cglib_Invocation us=new cglib_Invocation();
		Enhancer enh=new Enhancer();
		enh.setSuperclass(UserServiceImpl.class);
		enh.setCallback(us);
		UserService uuss=(UserService)enh.create();
		System.out.println(uuss.getName("张三"));
		System.out.println(uuss.getAge(20));
		
	}

}

jdk动态代理是对接口方法的代理,代理子类实现了InvocationHandler接口

cglib动态代理是直接继承了Enhancer中的代理,代理子类实现了MethodInterceptor接口, 设置代理类UserServiceImpl.class,设置回调函数cglib_Invocation

你可能感兴趣的:(技术模块)