Mybatis 拦截器注册方式

在MyBatis中注册拦截器可以通过以下三种方式:
1. XML配置文件方式
在Mybatis的核心配置文件(mybatis-config.xml)中的标签下定义拦截器,并指定实现类。

xml 复制代码
<configuration>
    <!-- ...其他配置... -->
    <plugins>
        <plugin interceptor="com.example.MyInterceptor">
            <!-- 可以设置属性 -->
            <property name="propertyName" value="propertyValue"/>
        </plugin>
    </plugins>
</configuration>

2. Spring Boot自动配置方式
如果你的应用使用了Spring Boot和Mybatis-Spring-boot-starter,可以在Spring Bean配置类中通过@Configuration和@Bean注解来注册拦截器。

java 复制代码
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return configuration -> {
            // 创建并添加拦截器实例到配置中
            configuration.addInterceptor(new MyInterceptor());
        };
    }
}

3. 注解式注册(适用于Spring环境)
如果你希望在Spring环境下更灵活地控制拦截器的作用范围,也可以利用@Intercepts和@Component注解来注册拦截器。

java 复制代码
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.stereotype.Component;

@Component
@Intercepts({ 
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
    // 其他要拦截的方法...
})
public class MyInterceptor implements Interceptor {

    // 实现Interceptor接口方法
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 拦截逻辑...
        return invocation.proceed();
    }

    // 其他方法...
}
相关推荐
天空鸟_时光不老15 小时前
13-亮点提炼:把技术说辞翻译成业务价值
java·spring boot·spring·spring cloud·mybatis
禾小西2 天前
Redis AOF 日志:宕机了,如何避免数据丢失?
java·redis·mybatis
天空鸟_时光不老2 天前
09-RAG问答系统落地:从默认分割器的坑到Milvus召回调优
java·人工智能·spring boot·spring·spring cloud·maven·mybatis
西凉的悲伤2 天前
MyBatis 中 association 与 collection 详解
java·mybatis
天空鸟_时光不老2 天前
10-Agent安全隐患与SQL执行层加固
java·数据库·人工智能·sql·spring·maven·mybatis
jianjinwssy3 天前
MyBatis-Plus 从入门到实战:常用功能与核心原理
java·mybatis
ss2733 天前
AI全栈实战 | 3.6-01 数据库与 ORM:学过 MyBatis 再看 SQLAlchemy,才知道“半自动“和“全自动“差在哪
数据库·mybatis
代码什么用6 天前
使用javassist生成类 && MyBatis中接口代理机制及使用
mybatis
paopaokaka_luck7 天前
非遗文物数字化小程序(AI非遗问答、ONNX图像识别、协同过滤推荐、ECharts数据分析、非遗知识浏览与互动、文创商城订单闭环、文化活动报名签到、社区交流)
javascript·spring boot·mysql·数据分析·echarts·mybatis
韩曙亮7 天前
【JavaEE】MyBatis 基本用法 ⑤ ( 单条件查询 | 多条件查询 | 多条件动态查询 | 单条件动态查询 )
java·sql·java-ee·mybatis·mapper·sql映射