假如有如下UserMapper接口:
public interface UserMapper {
List<SysUser> selectAll();
}
创建一个代理类MapperProxy.java,代码如下:
import org.apache.ibatis.session.SqlSession;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
public class MapperProxy implements InvocationHandler{
private Class<?> mapperInterface;
private SqlSession sqlSession;
public MapperProxy(Class<?> mapperInterface, SqlSession sqlSession) {
this.mapperInterface = mapperInterface;
this.sqlSession = sqlSession;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("-------------------------------");
List<Object> list = sqlSession.selectList(
mapperInterface.getCanonicalName() + "." + method.getName());
return list;
}
}
测试代码如下:
public static void main(String[] args) {
SqlSession sqlSession = getSqlSession();
MapperProxy mapperProxy = new MapperProxy(UserMapper.class,sqlSession);
UserMapper userMapper = (UserMapper) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{UserMapper.class},mapperProxy);
List<SysUser> users = userMapper.selectAll();
System.out.println(users.size());
}