spring-mybits 拦截器–注解
背景:在数据更新的时候需要记录日志和清理缓存
解决方案:使用mybits拦截器,拦截update 和 insert
在这里需要获得参数 org.apache.ibatis.plugin.Invocation;
拦截器配置
package com.bear.hapure.mybits;
import com.bear.hapure.utils.HapBeanHelper;
import java.util.Map;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.bear.hapure.mybits.interceptortask.UpdateInterceptorTask;
/**
*
* @author Dell
*/
@Intercepts({
@Signature(
type = Executor.class,
method = "update", args = {MappedStatement.class, Object.class})})
public class UpdateInterceptor implements Interceptor {
@Autowired
private ApplicationContext applic;
@Override
public Object intercept(Invocation invocation) throws Throwable {
Map<String, UpdateInterceptorTask> beanMap = applic.getBeansOfType(UpdateInterceptorTask.class);
if (beanMap != null) {
for (UpdateInterceptorTask task : beanMap.values()) {
task.runTask(invocation);
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
拦截器注册
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mybatis_mapper/*.xml" />
<property name="typeAliasesPackage" value="com.bear.hapure.docm.entity" />
<property name="plugins">
<array>
<bean class="com.bear.hapure.mybits.UpdateInterceptor"></bean>
</array>
</property>
</bean>
定义接口
package com.bear.hapure.mybits.interceptortask;
import org.apache.ibatis.plugin.Invocation;
/**
*
* @author Dell
*/
public interface UpdateInterceptorTask {
public void runTask(Invocation invocation);
}
任务实现类B
package com.bear.hapure.mybits.interceptortask;
import org.apache.ibatis.plugin.Invocation;
import org.springframework.stereotype.Component;
/**
*
* @author Dell
*/
@Component
public class BTask implements UpdateInterceptorTask{
@Override
public void runTask(Invocation invocation) {
System.out.println("BBBBB");
}
}
任务实现类A
@Component
public class ATask implements UpdateInterceptorTask{
@Override
public void runTask(Invocation invocation) {
System.out.println("AAAAAA");
}
}
注入
<context:component-scan base-package="com.bear.hapure.mybits.interceptortask"/>