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

    // 其他方法...
}
相关推荐
张较瘦_10 小时前
SpringBoot3 | MyBatis-Plus 搞定宠物管理:从0到1实现增删改查
mybatis·宠物
沙白猿17 小时前
Redis报错:A bean with that name has already been defined in class path resource
spring boot·redis·mybatis
小马爱打代码19 小时前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
柒.梧.2 天前
SSM常见核心面试问题深度解析
java·spring·面试·职场和发展·mybatis
rabbit_pro2 天前
Java使用Mybatis-Plus封装动态数据源工具类
java·python·mybatis
IT_Octopus2 天前
java 实体属性 Map 解决 mybatis-plus wrapper selectone 查mysql json类型为null 问题
java·mysql·mybatis
Dolphin_Home2 天前
MyBatis 核心属性详解笔记(由浅入深)
笔记·mybatis
一直都在5722 天前
MyBatis入门:CRUD、参数处理与防 SQL 注入
java·sql·mybatis
while(1){yan}2 天前
MyBatis Generator
数据库·spring boot·java-ee·mybatis