Java动态代理
JDK的动态代理,只适用面向接口编程
定义接口
public interface UserService {
public void buy(String userName);
public String Say(String words);
}
实现类
public class UserServiceImpl implements UserService {
@Override
public void buy(String userName) {
System.out.println("用户:"+userName);
}
@Override
public String Say(String words) {
System.out.println("发言:"+words);
return "**********"+ words;
}
}
织入类,需要实现接口java.lang.reflect.InvocationHandler
public class JdkInvocation implements InvocationHandler {
private Object target;
public JdkInvocation(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始执行动态代理");
Object obj = method.invoke(target, args);
System.out.println("完成执行动态代理");
return obj;
}
}
测试
public static void main(String[] args) {
//目录对象
UserService user =new UserServiceImpl();
//织入类
JdkInvocation handler =new JdkInvocation(user);
//动态代理类
UserService user2 =(UserService)Proxy.newProxyInstance(user.getClass().getClassLoader(),user.getClass().getInterfaces(), handler);
user2.buy("cwg");
String words = user2.Say("good");
System.out.println(words);
}
执行结果:
开始执行动态代理
用户:cwg
完成执行动态代理
开始执行动态代理
发言:good
完成执行动态代理
**********good
CGLIG动态代理
目标类
public class UserService {
public String Say(String words){
System.out.println("用户发言:"+words);
return "用户发言:"+words;
}
}
代理类:
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
public class Proxy implements MethodInterceptor
{
private Enhancer enhancer =new Enhancer();
public Object getProxy(Class clz) {
enhancer.setSuperclass(clz);
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,MethodProxy arg3) throws Throwable {
System.out.println("进入代理类");
Object result = arg3.invokeSuper(arg0, arg2);
System.out.println("结束代理类");
return result;
}
}
测试:
public static void main(String[] args) {
Proxy proxy = new Proxy();
UserService user =(UserService) proxy.getProxy(UserService.class);
String str = user.Say("Hello");
System.out.println(str);
}
执行结果:
进入代理类
用户发言:Hello
结束代理类
用户发言:Hello