关于springboot:springbootmybatis拦截器不生效问题分析

50次阅读

共计 2368 个字符,预计需要花费 6 分钟才能阅读完成。

一、环境信息
SpringBoot:2.3.6.RELEASE
Mybatis-plus:3.3.1
二、碰到问题
明天因业务零碎性能须要,应用 mybatis 的拦截器对 ORACLE 的数据库会话进行用户以后语言环境设置 (NLS_LANGUAGE), 碰到拦截器代码不失效的问题,特此记录下来,不便未来查阅。
三、代码如下:
1、在 Mybatis 的 @Configuration 相干代码增加如下代码(主动注入到拦截器链):

/**
 * 更改会话状态
 *
 * @return
 */
@Bean
public AlterSessionInterceptor alterSessionInterceptor() {return new AlterSessionInterceptor();
}

2、拦截器代码(拦挡 StatementHandler 的 prepare 办法,取到 Connection 执行 ALTER SESSION 的语句):
/**

  • <p>
  • 更改会话解析器
  • </p>
    *
  • @since 2021/7/14
    */

@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = “prepare“, args = {Connection.class, Integer.class})})
public class AlterSessionInterceptor implements Interceptor {

@Override
public Object intercept(Invocation invocation) throws Throwable {Object[] args = invocation.getArgs();
    Connection connection = (Connection) args[0];
    if ("Oracle".equalsIgnoreCase(connection.getMetaData().getDatabaseProductName())) {
        Statement statement = null;
        try {statement = connection.createStatement();
            String locale = RequestHelper.getCurrentLocale();
            if ("en_GB".equalsIgnoreCase(locale)) {statement.execute("ALTER SESSION SET NLS_LANGUAGE='AMERICAN'");
            } else {statement.execute("ALTER SESSION SET NLS_LANGUAGE='SIMPLIFIED CHINESE'");
            }
        } finally {statement.close();
        }
    }
    return invocation.proceed();}

}
在运行调试时发现代码无奈执行到拦挡逻辑,通过参考分页插件代码,发现须要重载以下办法(代码默认是只有实现 intercept 这个接口,然而实际上须要多加以下插件的解决逻辑才能够,才会启用 Plugin 的 Proxy):

@Override
public Object plugin(Object target) {if (target instanceof StatementHandler) {return Plugin.wrap(target, this);
    }
    return target;
}

最终拦截器代码如下:
/**

  • <p>
  • 更改会话解析器
  • </p>
    *
  • @since 2021/7/14
    */

@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = “prepare”, args = {Connection.class, Integer.class})})
public class AlterSessionInterceptor implements Interceptor {

@Override
public Object intercept(Invocation invocation) throws Throwable {Object[] args = invocation.getArgs();
    Connection connection = (Connection) args[0];
    if ("Oracle".equalsIgnoreCase(connection.getMetaData().getDatabaseProductName())) {
        Statement statement = null;
        try {statement = connection.createStatement();
            String locale = RequestHelper.getCurrentLocale();
            if ("en_GB".equalsIgnoreCase(locale)) {statement.execute("ALTER SESSION SET NLS_LANGUAGE='AMERICAN'");
            } else {statement.execute("ALTER SESSION SET NLS_LANGUAGE='SIMPLIFIED CHINESE'");
            }
        } finally {statement.close();
        }
    }
    return invocation.proceed();}

@Override
public Object plugin(Object target) {if (target instanceof StatementHandler) {return Plugin.wrap(target, this);
    }
    return target;
}

@Override
public void setProperties(Properties properties) {// to do nothing}

}

正文完
 0