SpringBoot项目中如何保证自定义的Mybatis拦截器在PageHelper之前执行?

如果项目中引入的是pagehelper-spring-boot-starter包,可能会遇到SqlSession拦截器执行顺序的问题。starter模式下,PageHelper在PageHelperAutoConfiguration里进行的配置,这样就不能手动设置拦截器的顺序。Mybatis拦截器是先添加的后执行,因此可以采用观察者模式在Spring容器初始化完成之后再添加自定义的拦截器。Spring提供了一个这样的接口:
在这里插入图片描述
自定义的Listener代码如下:

@Component
public class SqlSessionListener implements ApplicationListener<SqlSessionEvent> {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Override
    public void onApplicationEvent(SqlSessionEvent event) {
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            sqlSessionFactory.getConfiguration().addInterceptor(new MyInterceptor());
        }
        System.out.println();
    }
}

这里需要自定义一个Event,这个Event要继承ApplicationEvent,代码如下:

public class SqlSessionEvent extends ApplicationContextEvent {

    /**
     * Create a new ContextStartedEvent.
     *
     * @param source the {@code ApplicationContext} that the event is raised for
     *               (must not be {@code null})
     */
    public SqlSessionEvent(ApplicationContext source) {
        super(source);
    }
}

这个Event通过ApplicationContext发布出去即可。

public class TestApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TestApplication.class, args);
        context.publishEvent(new SqlSessionEvent(context));
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45497155/article/details/106025321