springboot项目中MyBatis自定义拦截器
mybatis实现拦截器需要使用它自有的Interceptor接口和@Intercepts注解
-
Interceptor接口中包含三个方法:
- intercept:主要是写我们具体业务逻辑,比如针对增删改sql语句添加更新日期。
- plugin:生成代理对象
- setProperties:设置拦截器属性
-
@Intercepts
作用:声明这是一个拦截器。
属性:Signature(注解)
@Signature:要拦截的具体方法
属性: type-拦截接口(四种类型,具体看官网 https://mybatis.net.cn/configuration.html#plugins ),method-拦截的方法(update,insert,select),args-重载时根据参数列表确定要拦截的方法
简单代码实现:
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.Signature; import org.springframework.stereotype.Component; import java.util.Properties; @Component @Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class MyBatisIntercept implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { /** * 业务逻辑,例如: * 在修改时进行修改时间的插入 */ return null; } @Override public Object plugin(Object target) { /** * 生产代理对象 */ return null; } @Override public void setProperties(Properties properties) { /** * 设置拦截器的属性 */ } }
声明完拦截器后需要将其装入mybatis中:
import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class MyBatisConfig { @Autowired private MyBatisIntercept myBatisIntercept; @Autowired private DataSource dataSource; @Bean public SqlSessionFactoryBean sqlSessionFactoryBean() { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); //将自定义拦截器装入mybatis bean.setDataSource(dataSource); bean.setPlugins(myBatisIntercept); return bean; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)