静态代理
public class StaticProxy implements Man {
private Man man;
public StaticProxy() {
man = new ManImpl();
}
@Override
public void look(String bookName) {
before();
man.look(bookName);
after();
}
private void before(){
System.out.println("before");
}
private void after(){
System.out.println("after");
}
public static void main(String[] args){
Man man = new StaticProxy();
man.look("静态代理");
}
}
JDK 动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by on 2017/12/9.
* JDK 动态代理
*/
public class DynamicProxy implements InvocationHandler {
private Object target;
public DynamicProxy(Object target) {
this.target = target;
}
public <T> T getProxy(){
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object result = method.invoke(target,args);
after();
return result;
}
private void before(){
System.out.println("before");
}
private void after(){
System.out.println("after");
}
public static void main(String[] args){
DynamicProxy dynamicProxy = new DynamicProxy(new ManImpl());
Man man = dynamicProxy.getProxy();
man.look("JDK 动态代理");
}
}
CGLib 动态代理
1)引入maven依赖
<!-- CGLibproxy代理 -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
2)代码实现
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Created by on 2017/12/9.
* CGLib 动态代理
*/
public class CGLibProxy implements MethodInterceptor {
public <T> T getProxy(Class<T> cls){
return (T) Enhancer.create(cls,this);
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
before();
Object result = methodProxy.invokeSuper(o,objects);
after();
return result;
}
private void before(){
System.out.println("before");
}
private void after(){
System.out.println("after");
}
public static void main(String[] args){
CGLibProxy cgLibproxy = new CGLibProxy();
Man man = cgLibproxy.getProxy(ManImpl.class);
man.look("CGLib 动态代理");
}
}