Java中如何向自定义MySQL StatementInterceptorV2传递属性?
给自定义StatementInterceptorV2传递自定义属性的实现方案
我之前也做过类似的自定义拦截器开发,刚好能给你分享两种靠谱的实现方式,帮你把自定义属性传递进去:
方式一:通过连接属性传递(推荐,线程安全)
Connector/J的拦截器初始化时会拿到连接属性对象,你可以把自定义参数直接塞进连接配置里,然后在拦截器的init方法里读取,这是最规范的做法。
步骤1:在连接配置中添加自定义参数
修改你的连接创建代码,除了指定拦截器全类名,额外加入自定义属性:
public Connection getDatabaseConnection(String jdbcUrl, String dbUser, String dbPassword) throws SQLException { Properties dbProps = new Properties(); dbProps.put("user", dbUser); dbProps.put("password", dbPassword); // 指定自定义拦截器的完整类路径 dbProps.put("statementInterceptors", "com.yourteam.YourCustomInterceptor"); // 加入自定义属性,前缀用自己的标识避免和内置属性冲突 dbProps.put("my.interceptor.customStr", "这是任意自定义字符串"); dbProps.put("my.interceptor.customNum", "999"); return DriverManager.getConnection(jdbcUrl, dbProps); }
步骤2:在拦截器的init方法中读取参数
自定义拦截器实现StatementInterceptorV2接口后,重写init方法获取属性:
public class YourCustomInterceptor implements StatementInterceptorV2 { private String customStr; private int customNum; @Override public void init(ConnectionProperties props) throws SQLException { // 读取字符串类型的自定义属性 this.customStr = props.getStringProperty("my.interceptor.customStr"); // 读取数字类型属性并做类型转换 String numStr = props.getStringProperty("my.interceptor.customNum"); if (numStr != null) { this.customNum = Integer.parseInt(numStr); } } // 在其他拦截方法中就可以直接使用这些自定义属性了 @Override public ResultSet postProcess(String sql, Statement interceptedStatement, ResultSet originalResultSet, Connection connection, int warningCount, boolean noIndexUsed, boolean noGoodIndexUsed, SQLException statementException) { System.out.println("拿到自定义字符串:" + customStr); System.out.println("拿到自定义数字:" + customNum); return originalResultSet; } // 按需实现其他接口方法(preProcess、destroy等) }
方式二:静态变量/构造函数传递(不推荐,仅限单连接场景)
如果你的应用只会用到单个数据库连接,也可以通过静态变量或者构造函数传参,但这种方式在连接池场景下会出现参数共享的线程安全问题,所以只适合简单场景:
// 自定义拦截器类 public class YourCustomInterceptor implements StatementInterceptorV2 { private static String customParam; // 静态方法设置参数 public static void setCustomParam(String param) { customParam = param; } // 在拦截方法中使用 @Override public void preProcess(String sql, Statement interceptedStatement, Connection connection) throws SQLException { System.out.println("静态参数:" + customParam); } // 其他方法实现... } // 连接前设置参数 YourCustomInterceptor.setCustomParam("静态传递的参数"); // 再创建数据库连接...
注意点
- 自定义属性命名最好加专属前缀(比如
my.interceptor.),避免和Connector/J内置属性重名 - 如果用JDBC URL传递参数,格式是:
jdbc:mysql://host:port/db?statementInterceptors=com.yourteam.YourCustomInterceptor&my.interceptor.customStr=xxx
内容的提问来源于stack exchange,提问作者kibowki
相关产品推荐
相关产品推荐

