1 UserServiceProxyFactory4代码
package www.test.c_proxy;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import www.test.service.UserService;
import www.test.service.UserServiceImpl;
public class UserServiceProxyFactory4 implements MethodInterceptor {
public UserService getUserServiceProxy(){
Enhancer en = new Enhancer(); //帮我们生成代码对象
en.setSuperclass(UserServiceImpl.class); //设置对谁进行代理
en.setCallback(this); //代理要做什么
UserService us = (UserService) en.create(); //创建代理对象
return us;
}
@Override
public Object intercept(Object proxyObj, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable {
System.out.println("目标方法前面的操作");
//执行原有方法
Object invokeSuper = methodProxy.invokeSuper(proxyObj, arg);
System.out.println("目标方法之后的操作");
return invokeSuper;
}
}
2 测试
package www.test.c_proxy;
import org.junit.Test;
import www.test.service.UserService;
import www.test.service.UserServiceImpl;
public class Demo3 {
@Test
public void fun1(){
UserServiceProxyFactory4 proxyFactory = new UserServiceProxyFactory4();
UserService usProxy = proxyFactory.getUserServiceProxy();
usProxy.find();
//判断代理对象是否属于被代理对象类型
//代理对象继承了被代理对象==>true
System.out.println(usProxy instanceof UserServiceImpl);//true;
}
}