拦截器可在mybatis进行sql底层处理的时候执行额外的逻辑,最常见的就是分页逻辑、对结果集进行处理过滤敏感信息等。
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction) {
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
从上面的代码可以看到mybatis支持的拦截类型只有四种(按拦截顺序)
1.Executor 执行器接口
2.StatementHandler sql构建处理器
3.ParameterHandler 参数处理器
4.ResultSetHandler 结果集处理器
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<>();
// 遍历定义的拦截器,对拦截的对象进行包装
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
#Interceptor
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
default Object plugin(Object target) {
return Plugin.wrap(target, this);
}
default void setProperties(Properties properties) {
// NOP
}
}
mybatis拦截器本质上使用了jdk动态代理,interceptorChain拦截器链中存储了用户定义的拦截器,会遍历进行对目标对象代理包装。
用户自定义拦截器类需要实现Interceptor接口,以及实现intercept方法,plugin和setProperties方法可重写,plugin方法一般不会改动,该方法调用了Plugin的静态方法wrap实现了对目标对象的代理
public class Plugin implements InvocationHandler {
// 拦截目标对象
private final Object target;
// 拦截器对象-执行逻辑
private final Interceptor interceptor;
// 拦截接口和拦截方法的映射
private final Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
// 获取jdk代理对象
public static Object wrap(Object target, Interceptor interceptor) {
// 存储拦截接口和拦截方法的映射
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
// 获取拦截目标对象实现的接口,若为空则不代理
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 获取需要拦截的方法集合,若不存在则使用目标对象执行
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
// Invocation存储了目标对象、拦截方法以及方法参数
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
// 获取Intercepts注解值不能为空
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
// key 拦截的类型
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
try {
// 获取拦截的方法
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
/**
* Returns method signatures to intercept.
*
* @return method signatures
*/
Signature[] value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
/**
* Returns the java type.
*
* @return the java type
*/
Class<?> type();
/**
* Returns the method name.
*
* @return the method name
*/
String method();
/**
* Returns java types for method argument.
* @return java types for method argument
*/
Class<?>[] args();
}
可以看到,当被拦截的方法被执行时主要调用自定义拦截器的intercept方法,把拦截对象、方法以及方法参数封装成Invocation对象传递过去。
在getSignatureMap方法中可以看到,自定义的拦截器类上需要添加Intercepts注解并且Signature需要有值,Signature注解中的type为需要拦截对象的接口(Executor.class/StatementHandler/ParameterHandler/ResultSetHandler),method为需要拦截的方法的方法名,args为拦截方法的方法参数类型。
接下来举一个拦截器实现对结果集下划线转驼峰的例子来简要说明
/**
* @author dxu2
* @date 2022/7/14
* map结果转驼峰
*/
@Intercepts(value = {@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class MyInterceptor implements Interceptor {
@SuppressWarnings("unchecked")
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 调用目标方法
List<Object> result = (List<Object>) invocation.proceed();
for (Object o : result) {
if (o instanceof Map) {
processMap((Map<String, Object>) o);
} else {
break;
}
}
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
private void processMap(Map<String, Object> map) {
Set<String> keySet = new HashSet<>(map.keySet());
for (String key : keySet) {
if ((key.charAt(0) >= 'A' && key.charAt(0) <= 'Z') || key.indexOf("_") > 0) {
Object value = map.get(key);
map.remove(key);
map.put(camel(key), value);
}
}
}
// 下划线转驼峰
private String camel(String fieldName) {
StringBuffer stringBuffer = new StringBuffer();
boolean flag = false;
for (int i = 0; i < fieldName.length(); i++) {
if (fieldName.charAt(i) == '_') {
if (stringBuffer.length() > 0) {
flag = true;
}
} else {
if (flag) {
stringBuffer.append(Character.toUpperCase(fieldName.charAt(i)));
flag = false;
} else {
stringBuffer.append(Character.toLowerCase(fieldName.charAt(i)));
}
}
}
return stringBuffer.toString();
}
}
这个例子拦截的是ResultSetHandler的handleResultSets方法,这个方法是用来对结果集处理的,看intercept方法首先调用了目标对象的方法接着强转为List<Object>类型,这里为什么可以强转呢,因为我们可以看到handleResultSets方法定义<E> List<E> handleResultSets(Statement stmt) throws SQLException; 返回的是List类型,然后遍历列表,若元素是map类型的再进行处理把key值转化为驼峰形式重新put到map中。
最后不要忘了把自定义的拦截器添加到配置中,这边是使用xml配置的,添加完后接着运行测试代码,可以看到列user_id已经转换成驼峰形式了。
<plugins>
<plugin interceptor="org.apache.ibatis.study.interceptor.MyInterceptor">
</plugin>
</plugins>
#mapper接口
List<Map> selectAllUsers();
#mapper.xml
<select id="selectAllUsers" resultType="map">
select user_id, username, password, nickname
from user
</select>
#java测试类
public class Test {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml")) {
// 构建session工厂 DefaultSqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println(userMapper.selectAllUsers());
}
}
}

使用Ruby1.8.6/Rails2.3.2我注意到在我的任何ActiveRecord模型类上调用的任何方法都返回nil而不是NoMethodError。除了烦人之外,这还破坏了动态查找器(find_by_name、find_by_id等),因为即使存在记录,它们也总是返回nil。不从ActiveRecord::Base派生的标准类不受影响。有没有办法追踪在ActiveRecord::Base之前拦截method_missing的是什么?更新:切换到1.8.7后,我发现(感谢@MichaelKohl)will_paginate插件首先处理method_missing。但是will_pa
我目前有一个父类(superclass),它有一个函数,我希望所有子类在它的每个函数中调用该函数。该函数的行为应该像rails中的before_filter函数,但我不确定如何去实现before_filter。这是一个例子classSuperclassdefbefore_each_methodputs"BeforeMethod"#thisissupposedtobeinvokedbyeachextendingclass'methodendendclassSubclass 最佳答案 这是一种方法:classSuperclassdefb
我正在使用rails3.0.3、ruby1.9.2-p180、邮件(2.2.13)。我正在尝试设置邮件拦截器,但出现以下错误/home/abhimanyu/Aptana_Studio_3_Workspace/delivery_health_dashboard_03/config/initializers/mailer_config.rb:16:in`':uninitializedconstantDevelopmentMailInterceptor(NameError)我该如何解决?我使用的代码如下所示:config/initializer/mailer_config.rbActionM
我的angular-cli(v1.5.1,angularv5)应用程序中有以下两个环境:开发产品Dev使用模拟数据,我提供了一个http拦截器。Pro使用实时休息api。我如何在dev上提供http拦截器,而不是在pro上?我已经尝试了以下方法,但它不起作用:{provide:HTTP_INTERCEPTORS,useFactory:()=>{if(environment.useMockBackend===true){returnMockHttpInterceptor;}returnfalse;},multi:true} 最佳答案
我正在使用Capybara、Cucumber和Poltergeist。我正在测试附加到表单提交按钮的JavaScript函数,该函数旨在捕获提交事件并阻止它(在后台执行AJAX请求)。使用和不使用AJAX,页面最终看起来都一样,但AJAX方法要快得多,并且不会中断浏览体验等。我可以做些什么来测试表单确实没有提交,并且更改是动态AJAX调用而不是重新加载的结果? 最佳答案 @jules答案的修改版本:describe"Mypage",:jsdoit"reloadswhenitshould"dovisit"/"expect_page_t
我正在尝试编写一个拦截器以使用Angular向所有HTTP请求添加一个token。我大致使用这里给出的食谱-https://thinkster.io/interceptors因此代码使用了http模块工厂和一个tokenInterceptor()函数。我可以成功地将token作为header添加到请求中-但现在当它通过拦截器时,它会被某种CORS阻塞机制阻塞。我在Chrome控制台中收到此错误-XMLHttpRequestcannotloadhttp://127.0.0.1:/.Responsetopreflightrequestdoesn'tpassaccesscontrolchec
我想将一些副作用与每个数组访问器相关联,例如a[i]。例如,如果副作用是向控制台写入消息,则以下程序:vararray=[1,2,3]vartotal=0;for(variinarray){total+=array[i]}console.log(total);应该返回如下输出:1//accessa[0]2//accessa[1]3//accessa[2]6//printoriginaltotal如果我对拦截数组方法push感兴趣,我会使用此博客中的技术post并提供了一个拦截器:var_push=Array.prototype.push;Array.prototype.push=fun
是否可以使用javascript拦截从页面发出的每个请求?即单击链接、加载图像、ajax请求... 最佳答案 一句话,没有。没有任何地方可以Hook以获取所有请求。话虽如此,您可以使用javascript在链接上放置事件处理程序,查看图像标签的src属性等。没有“通用”的方式来连接所有AJAX请求-这取决于您使用的库。还有其他需要考虑的,比如CSS背景图片,Flash(如果一个flash文件发出请求怎么办?)。如果可能,您应该使用浏览器本身(例如Firebug)或代理(例如Fiddler)或数据包嗅探器(例如Ethereal...现
我遇到的问题是,当我尝试执行类似以下代码的操作时,窗口将被弹出窗口阻止程序阻止。我正在使用getScript以便我可以发出跨域请求。我正在使用jQuery1.4.2来执行以下操作。将被阻止的代码示例://Codethatgetsblockedbypop-upblockers$(document).ready(function(){$(".popup").click(function(){$.getScript("URL_To_A_Javascript_File",function(){window.open("dynamicURL","_blank");});});});越过拦截器但未
有什么方法可以拦截通过jquery发出的ajax请求,向其中插入额外的变量吗?我知道.ajaxStart()允许您注册一个回调,该回调在ajax请求开始时触发一个事件,但我正在寻找一种方法来取消该ajax请求,如果它满足某些条件(例如url),在其内容中插入更多变量,然后提交。这是用于第三方软件的插件,其自身代码无法直接更改。编辑:看起来像.ajaxSetup()允许您设置一些与ajaxRequests相关的全局变量。如果我注册了一个beforeSend函数,该函数是否能够取消请求以在满足特定条件时做出不同的请求? 最佳答案 想通了