mybatis註冊攔截器

IamHzc發表於2024-10-11

背景:有時候直接宣告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());
    }
}

相關文章