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();
    }

    // 其他方法...
}
相关推荐
独断万古他化7 小时前
【SSM开发实战:博客系统】(三)核心业务功能开发与安全加密实现
spring boot·spring·mybatis·博客系统·加密
fengxin_rou11 小时前
[Redis从零到精通|第四篇]:缓存穿透、雪崩、击穿
java·redis·缓存·mybatis·idea·多线程
老毛肚21 小时前
MyBatis插件原理及Spring集成
java·spring·mybatis
马尔代夫哈哈哈1 天前
MyBatis 入门与实战:从配置到CRUD一站式指南
mybatis
Jul1en_1 天前
【MyBatis/plus】核心配置、插件与 MyBatis-Plus 构造器 Wrapper
mybatis
LiZhen7981 天前
SpringBoot 实现动态切换数据源
java·spring boot·mybatis
我是Superman丶1 天前
在 PostgreSQL 中使用 JSONB 类型并结合 MyBatis-Plus 实现自动注入,主要有以下几种方案
数据库·postgresql·mybatis
Pluto_CSND1 天前
基于mybatis-generator插件生成指定数据表的实体类、xml文件和dao层接口
mybatis
indexsunny1 天前
互联网大厂Java面试实战:微服务与Spring生态技术解析
java·spring boot·redis·kafka·mybatis·hibernate·microservices
手握风云-1 天前
JavaEE 进阶第十六期:MyBatis,查询请求的生命周期全景图(一)
java·java-ee·mybatis