动态代理看这篇文章很详细:https://www.cnblogs.com/gonjan-blog/p/6685611.html
上述是正常动态代理的思路
来看看Mybatis的源码
简单调用一下mybatis
SqlSession sqlSession = factory.openSession();
//我们来分析sqlSession.getMapper(UserMapper.class);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
选择DefaultSqlSession来看
@Override
//这个type就是我们传入的UserMapper.class
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
继续到configuration.getMapper(type, this);
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
继续深入,还没到动态代理的部分
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);
}
}
很显然这个动态代理交给了mapperProxyFactory来实现的,我们进去看看
先看看他的构造
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
显然,他的跟我们传进去的接口Class进行关联,看看他的mapperProxyFactory.newInstance(sqlSession);
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
emm,开始眼熟起来了Proxy.newProxyInstance,这个函数不就是动态代理的方法吗,这波看看他的最后一个参数,mapperProxy 他的类是MapperProxy,进去看看,直接看他的invoke
@Override
public Object invoke(Object proxy, Method method, Object[] args)
//关于第一个变量proxy可以看https://blog.csdn.net/rock154/article/details/80059344?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.channel_param
throws Throwable {
try {
//如果代理类有实体直接用
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);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
进去mapperMethod.execute看看
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);
if (method.returnsOptional() &&
(result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
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;
}
就是执行对应的sql了。
思考了一下为什么mybatis没有实现接口的被代理类也能用,主要是在InvocationHandler.invoke根据穿进去的接口的Class来进行对应的操作,不一定要实体类对应metho.invoke;
自己写了一个,当然Mybatis功能更复杂,这只是鄙人之见。
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
Class<Hehe> heheClass = Hehe.class;
heheHandler classaa = new heheHandler(heheClass);
Hehe abc = (Hehe) Proxy.newProxyInstance(Hehe.class.getClassLoader(), new Class[]{Hehe.class}, classaa);
abc.haha();
}
static class heheHandler implements InvocationHandler {
Class<?> interfaceclass;
heheHandler(Class<?> interfaceclass){
this.interfaceclass =interfaceclass;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(666);
System.out.println(interfaceclass.getName());
return null;
}
}
public interface Hehe {
Object haha();
}