0.前言
代理模式,即通过代理对象访问目标对象。
先了解下JVM 的类加载机制中的加载阶段
- 通过一个类的全名或其它途径来获取这个类的二进制字节流
- 将这个字节流所代表的静态存储结构转化为方法区的运行时数据结构
- 在内存中生成一个代表这个类的 Class 对象,作为方法区中对这个类访问的入口
如果要实现的在方法前后增加处理,我们可以切入的对象或者说结点包括
在编译器修改源代码(静态代理)、在运行期字节码加载前修改字节码或字节码加载后动态创建代理类的字节码。
大体实现分为以下五种
- 静态代理
- 动态代理
- 动态字节码生成
- 自定义类加载器
- 字节码转换
下面分别介绍下每种方式的实现以及优缺点
1.静态代理
在代理类中实现接口中的方法,在实现方法里调用被代理类的方法,并在前后增加处理逻辑。
public class Test17_proxy {
public interface HelloService {
void sayHello();
}
public static class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("hello");
}
}
public static class HelloServiceForZhImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("你好");
}
}
public static class HelloServiceProxyImpl implements HelloService {
private HelloService hello;
public HelloServiceProxyImpl() {
}
public HelloServiceProxyImpl(HelloService hello) {
this.hello = hello;
}
@Override
public void sayHello() {
System.out.println("before");
hello.sayHello();
System.out.println("after");
}
}
public static void main(String[] args) {
// 通过不同的实体类的构造方法不同
HelloService helloService = new HelloServiceImpl();
HelloServiceProxyImpl helloServiceProxy = new HelloServiceProxyImpl(helloService);
helloServiceProxy.sayHello();
HelloService helloZHService = new HelloServiceForZhImpl();
HelloServiceProxyImpl helloServiceProxy1 = new HelloServiceProxyImpl(helloZHService);
helloServiceProxy1.sayHello();
}
}
2.动态代理
所谓动态代理,主要就发生在第一个阶段,这个阶段类的二进制字节流的来源可以有很多,在 Proxy 类中,就是运用了 ProxyGenerator.generateProxyClass 来为特定接口生成形式为 *$Proxy 的代理类的二进制字节流。
动态代理就是想办法根据接口或者目标对象计算出代理类的字节码然后加载进 JVM 中。
public class Test18_proxy {
public interface HelloService {
void sayHello();
String returnHello();
}
public static class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("hello");
}
@Override
public String returnHello() {
return "hello";
}
}
public static class HelloServiceForZhImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("你好");
}
@Override
public String returnHello() {
return "你好";
}
}
/**
* 实现InvocationHandler
*/
public static class HelloServiceProxyHandler implements InvocationHandler {
private Object obj;
/**
* 有参构造器,传入委托类的对象
* @param obj 委托类的对象(任意对象)
*/
public HelloServiceProxyHandler(Object obj) {
this.obj = obj;
}
public Object newProxyInstance() {
return Proxy.newProxyInstance(
//指定代理对象的类加载器
obj.getClass().getClassLoader(),
//代理对象需要实现的接口,可以同时指定多个接口
obj.getClass().getInterfaces(),
//方法调用的实际处理者,代理对象的方法调用都会转发到这里
this);
}
/**
* 重写invoke方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
// 是否需要获取返回对象
Object result = method.invoke(obj, args);
System.out.println("after");
// 需要返回就返回result,不需要就返回 null
return result;
}
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
HelloServiceProxyHandler proxyInvocationHandler = new HelloServiceProxyHandler(new HelloServiceImpl());
HelloService helloService = (HelloService) proxyInvocationHandler.newProxyInstance();
helloService.sayHello();
System.out.println(helloService.returnHello());
System.out.println("---------------分界线-----------------");
HelloServiceProxyHandler proxyInvocationHandler1 = new HelloServiceProxyHandler(new HelloServiceForZhImpl());
HelloService helloService1 = (HelloService) proxyInvocationHandler1.newProxyInstance();
helloService1.sayHello();
System.out.println(helloService1.returnHello());
}
}
3.动态字节码生成
使用动态字节码生成技术实现AOP原理:在运行期间目标字节码加载后,生成目标类的子类,将切面逻辑加入到子类中,Cglib实现AOP不实现接口,只有类的方法不是final即可。
配置文件
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
样例
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class Test19_proxy {
public static class HelloServiceImpl {
public void sayHello() {
System.out.println("hello");
}
}
public static class HelloServiceForZhImpl {
public String returnHello() {
return "你好";
}
}
public static class CglibInterceptor implements MethodInterceptor {
private Enhancer enhancer = new Enhancer();
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("before");
Object o = methodProxy.invokeSuper(obj, args);
System.out.println("after");
// 需要返回就返回o,不需要就返回 null
return o;
}
public Object newProxyInstance(Class<?> c) {
enhancer.setSuperclass(c);
enhancer.setCallback(this);
return enhancer.create();
}
}
public static void main(String[] args) {
CglibInterceptor cglibProxy = new CglibInterceptor();
HelloServiceImpl helloService = (HelloServiceImpl) cglibProxy.newProxyInstance(HelloServiceImpl.class);
helloService.sayHello();
System.out.println("---------------分界线-----------------");
CglibInterceptor cglibProxy1 = new CglibInterceptor();
HelloServiceForZhImpl helloService1 = (HelloServiceForZhImpl) cglibProxy1.newProxyInstance(HelloServiceForZhImpl.class);
System.out.println(helloService1.returnHello());
}
}
4.自定义类加载器
实现一个自定义类加载器,在类加载到JVM之前直接修改类的方法,并将切入逻辑织入到这个方法里,然后将修改后的字节码文件交给JVM运行。
javassist是一个编辑字节码的框架,可以很简单操作字节码。它可以在运行期定义或修改Class。使用Javassist实现AOP的原理是在字节码加载前直接修改需要切入的方法,比使用Cglib实现AOP更加高效。
5.字节码转换
自定义的类加载器实现AOP只能拦截自己加载的字节码,有没有能够监控所有类加载器加载字节码?——>有,使用Instrumentation,它是Java 5提供的新特性。使用Instrumentation可以构建一个字节码转换器,在字节码加载前进行转换。使用Instrumentation和javassist实现AOP。
6.各种方式的对比
7.Mybatis中的动态代理
第一步获取代理对象
A mapper = session.getMapper(A.class);
1.DefaultSqlSession的getMapper方法;
@Override
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
2.Configuration的getMapper方法
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
3.MapperRegistry类的getMapper方法
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
4.MapperProxyFactory的newInstance方法
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
5.MapperProxy
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 此方法所属类已经是MapperProxy对象则直接执行该方法
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 如果不是,则执行MapperProxy的逻辑
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
6.MapperMethod
private final SqlCommand command;
private final MethodSignature method;
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
还有executor.loader包使用了cglib或者javassist达到延迟加载的效果;
8.Spring的AOP
Spring默认采取的动态代理机制实现AOP,当动态代理不可用时(代理类无接口)会使用CGlib机制。