該攔截器的作用: 在進行增加、修改等操作時,給數據模型的一些通用操作屬性(如:創(chuàng)建人、創(chuàng)建時間、修改人、修改時間等)自動賦值。
該實現是在DAO層攔截,即存入DB前最后一層。后經分析,不是很合理,改為在service層攔截,用spring AOP來實現了,該代碼遂棄用。不過已經測試可用,記錄備忘。
package com.development;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
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;
/**
* 攔截器作用:給各實體對象在增加、修改時,自動添加操作屬性信息。
*/
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class }) })
public class OpeInfoInterceptor implements Interceptor
{
public Object intercept(Invocation invocation) throws Throwable
{
Object[] args = invocation.getArgs();
System.out.println("-----------參數攔截---------------------------------------------------");
System.out.println("02 當前線程ID:"+Thread.currentThread().getId());
//遍歷處理所有參數,update方法有兩個參數,參見Executor類中的update()方法。
for(int i=0;i
{
Object arg=args[i];
String className=arg.getClass().getName();
System.out.println(i + " 參數類型:"+className);
//第一個參數處理。根據它判斷是否給“操作屬性”賦值。
if(arg instanceof MappedStatement)
{//如果是第一個參數 MappedStatement
MappedStatement ms = (MappedStatement)arg;
SqlCommandType sqlCommandType = ms.getSqlCommandType();
System.out.println("操作類型:"+sqlCommandType);
if(sqlCommandType == SqlCommandType.INSERT || sqlCommandType==SqlCommandType.UPDATE)
{//如果是“增加”或“更新”操作,則繼續(xù)進行默認操作信息賦值。否則,則退出
continue;
}
else
{
break;
}
}
//第二個參數處理。(只有第二個程序才能跑到這)
if (arg instanceof Map)
{//如果是map,有兩種情況:(1)使用@Param多參數傳入,由Mybatis包裝成map。(2)原始傳入Map
System.out.println("這是一個包裝過的類型!");
Map map=(Map)arg;
for (Object obj : map.values())
{
setProperty(obj);
}
}
else
{//原始參數傳入
setProperty(arg);
}
}
return invocation.proceed();
}
/**
* 為對象的操作屬性賦值
* @param obj
*/
private void setProperty(Object obj)
{
try
{
//TODO: 根據需要,將相關屬性賦上默認值
BeanUtils.setProperty(obj, "createrUsername", "張三");
BeanUtils.setProperty(obj, "createDT", new Date());
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
public Object plugin(Object target)
{
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties)