JDK动态代理和CGLib代理
- JDK的代理
代理类
package com.xiaoyuxixi.yxrzbj;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by yuxi on 2018/1/6.
*/
public class JdkProxy implements InvocationHandler {
private Object target;//代理对象
public JdkProxy(Object object) {
this.target = object;
}
/**
* 获取代理对象
*
* @param <T>
* @return
*/
public <T> T getProxy() {
return (T) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this
);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object object = method.invoke(target, args);
after();
return object;
}
private void before() {
System.out.println("hello before");
}
private void after() {
System.out.println("hello after");
}
}
被代理接口
package com.xiaoyuxixi.yxrzbj;
/**
* Created by yuxi on 2018/1/6.
*/
public interface Hello {
public void sayHello() ;
}
被代理实现类
package com.xiaoyuxixi.yxrzbj;
/**
* Created by yuxi on 2018/1/6.
*/
public class HelloImpl implements Hello{
public void sayHello() {
System.out.println("hello jdk 动态代理");
}
}
启动类:
package com.xiaoyuxixi.yxrzbj;
/**
* Created by yuxi on 2018/1/6.
*/
public class Main {
public static void main(String[] args) {
// Hello hello = new HelloImpl();
// hello.sayHello();
//动态代理
Hello hello = new JdkProxy(new HelloImpl()).getProxy();
hello.sayHello();
}
}
jdk的动态代理是针对接口的,如果不是接口实现类的方式是无效的,这也是JDK代理的局限性,因此有了cglib代理。
- CGLib代理
cglib代理类:
package com.xiaoyuxixi.yxrzbj.cglib;
import org.mockito.cglib.proxy.Enhancer;
import org.mockito.cglib.proxy.MethodInterceptor;
import org.mockito.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Created by yuxi on 2018/1/6.
*/
public class CglibProxy implements MethodInterceptor {
private static CglibProxy cglibProxy = new CglibProxy();
private CglibProxy() {
}
public static CglibProxy getInstance() {
return cglibProxy;
}
/**
* 获取代理对象
*
* @param cls
* @param <T>
* @return
*/
public <T> T getProxy(Class<T> cls) {
return (T) Enhancer.create(cls, this);
}
public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {
before();
Object result = proxy.invokeSuper(target, args);
after();
return result;
}
private void before() {
System.out.println("hello cglib before");
}
private void after() {
System.out.println("hello cglib after");
}
}
启动类:
package com.xiaoyuxixi.yxrzbj.cglib;
import com.xiaoyuxixi.yxrzbj.jdkproxy.Hello;
import com.xiaoyuxixi.yxrzbj.jdkproxy.HelloImpl;
/**
* Created by yuxi on 2018/1/6.
*/
public class Main {
public static void main(String[] args) {
Hello hello = CglibProxy.getInstance(). getProxy(HelloImpl.class);
hello.sayHello();
}
}
aop 相关术语
- 通知 advice
- 连接点 joinpoint
- 切点 pointcut
- 切面
- 引入introduction