Loading

mybatis注册拦截器

背景:有时候直接声明bean的方式无法确保拦截器能够被Spring容器识别并正确地应用到MyBatis的环境中。
方式一:

@Configuration
public class MybatisConfig {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Bean
    public Interceptor mybatisTableNameInterceptor() {
        return new mybatisInterceptor();
    }

    @PostConstruct
    public void init() {
        sqlSessionFactory.getConfiguration().addInterceptor(mybatisInterceptor());
    }
}

方式二:

@Component
public class MybatisRunner implements ApplicationRunner {

    /**
     * @see DefaultListableBeanFactory
     */
    @Autowired
    private DefaultListableBeanFactory defaultListableBeanFactory;
    @Override
    public void run(ApplicationArguments args) {
        SqlSessionFactory sqlSessionFactory = defaultListableBeanFactory.getBean(SqlSessionFactory.class);
        sqlSessionFactory.getConfiguration().addInterceptor(new MybatisTableNameInterceptor());
    }
}
posted @ 2024-10-11 11:16  IamHzc  阅读(14)  评论(0编辑  收藏  举报