前提:将自定义的拦截器注入IOC容器。
1、创建自定义拦截器,实现Interceptor接口,重写interceptor()方法
2、在自定义拦截器上使用@Interceptors注解,在该注解中使用@Signature指定拦截的接口类型,方法名与参数类型。
实例:
/*
* Copyright (c) 2020, 2024, All rights reserved.
*
*/
package com.by.config;
import cn.hutool.core.util.ReflectUtil;
import cn.scl.core.threadlocal.LocalUserUtil;
import lombok.Singular;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
/**
* <p>Project: wms-root - ParameterPlugin</p>
* <p>Powered by scl On 2024-03-13 10:14:21</p>
* <p>描述:<p>
*
* @author 孙臣龙 [[email protected]]
* @version 1.0
* @since 17
*/
@Component
@Intercepts({@Signature(type = ParameterHandler.class,
method = "setParameters",
args = {PreparedStatement.class})})
public class ParameterPlugin implements Interceptor {
/**
* 统一设置lastUpdateBy的值
* @param invocation
* @return
* @throws Throwable
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
Object parameterObject = parameterHandler.getParameterObject();
Field lastUpdateBy = ReflectUtil.getField(parameterObject.getClass(), "lastUpdateBy");
if (lastUpdateBy != null) {
ReflectUtil.setFieldValue(parameterObject, lastUpdateBy, LocalUserUtil.getLocalUser().getNickName());
}
return invocation.proceed();
}
}
标签:拦截器,流程,ibatis,apache,org,MyBatis,import,lastUpdateBy
From: https://blog.csdn.net/qq_64847107/article/details/136675719