很多业务都需要创建用户,创建日期,更新用户,更新日期,这样的字段,只需要用Interceptor即可实现自动赋值。
首先创建四个注解
/**
* Declares a field as the one representing the principal that created the entity containing the field.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { FIELD, METHOD, ANNOTATION_TYPE })
public @interface CreatedBy {
}
/**
* Declares a field as the one representing the date the entity containing the field was created.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { FIELD, METHOD, ANNOTATION_TYPE })
public @interface CreatedDate {
}
/**
* Declares a field as the one representing the principal that recently modified the entity containing the field.
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { FIELD, METHOD, ANNOTATION_TYPE })
public @interface LastModifiedBy {
}
/**
* Declares a field as the one representing the date the entity containing the field was recently modified.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { FIELD, METHOD, ANNOTATION_TYPE })
public @interface LastModifiedDate {
}
下面是mybatis的拦截器,用了spring的注解工具类
/**
* 审计接口,自动注入用户id以及自动获取注入更新时间和创建时间
*/
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) })
public class AuditingInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
Object parameter = invocation.getArgs()[1];
Field[] fields = parameter.getClass().getDeclaredFields();
Date currentDate = new Date();
User currentUser = new User();
currentUser.setId(11111L);
if(SqlCommandType.UPDATE==sqlCommandType) {
for (Field field : fields) {
if (AnnotationUtils.getAnnotation(field, LastModifiedBy.class) != null) {
field.setAccessible(true);
field.set(parameter,currentUser.getId());
field.setAccessible(false);
}
if (AnnotationUtils.getAnnotation(field, LastModifiedDate.class) != null) {
field.setAccessible(true);
field.set(parameter,currentDate);
field.setAccessible(false);
}
}
} else if(SqlCommandType.INSERT==sqlCommandType){
for (Field field : fields) {
if (AnnotationUtils.getAnnotation(field, CreatedBy.class) != null) {
field.setAccessible(true);
field.set(parameter,currentUser.getId());
field.setAccessible(false);
}
if (AnnotationUtils.getAnnotation(field, CreatedDate.class) != null) {
field.setAccessible(true);
field.set(parameter,currentDate);
field.setAccessible(false);
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
}