我陷入了与 Java 中的数据源对象相关的问题。 我在数据源对象(org.apache.tomcat.jdbc.pool.DataSource)中设置了数据源连接参数。我想在调用 getConnection 方法之前从数据源对象获取这些参数,如果它捕获异常,则在 catch 中记录有意义的调试信息。
以下是到目前为止我尝试过的代码。我可以从元数据中获取所有连接参数,如下所示 [ex:- connection.getMetaData().getURL()],但如果 getConnection() 抛出异常,我想捕获异常并记录 url、密码、用户名作为日志。因此,我需要在它尝试创建数据库连接之前从数据源对象获取这些信息。
try {
// try to get the lookup name. If error empty string will be returned
jndiLookupName = connectionProperties.getProperty(RDBMSConstants.PROP_JNDI_LOOKUP_NAME);
datasource = InitialContext.doLookup(jndiLookupName);
connection = datasource.getConnection(); // WHEN THIS THROWS EXCEPTION...
logger.info(connection.getMetaData().getURL()); // these won't work since exception already thrown.
logger.info(connection.getMetaData().getUserName());
logger.info(connection.getMetaData().getDriverName());
logger.info(connection.getMetaData().getDriverVersion());
isConnected = true; // if no errors
logger.info("JDBC connection established with jndi config " + jndiLookupName);
} catch (SQLException e) {
//...I WANT ALL CONNECTION PARAMETERS (URL,PASSWORD,USERNAME) HERE
throw new SQLException("Connecting to database failed with jndi lookup", e);
}
当我远程调试时,我得到如下数据源对象..
org.apache.tomcat.jdbc.pool.DataSource@d47feb3{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=com.mysql.jdbc.Driver; maxActive=100; maxIdle=8; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=5000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=60000; testWhileIdle=false; testOnConnect=false; password=********; url=jdbc:mysql://localhost/wso2_mb_1; username=a; validationQuery=null; validationQueryTimeout=-1; validatorClassName=null; validationInterval=30000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=false; removeAbandonedTimeout=60; logAbandoned=false; connectionProperties=null; initSQL=null; jdbcInterceptors=ConnectionState;StatementFinalizer;org.wso2.carbon.ndatasource.rdbms.ConnectionRollbackOnReturnInterceptor;; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; suspectTimeout=0; alternateUsernameAllowed=false; commitOnReturn=false; rollbackOnReturn=false; useDisposableConnectionFacade=true; logValidationErrors=false; propagateInterruptState=false; ignoreExceptionOnPreLoad=false; }
我可以看到所有的 url、用户名和密码参数都在那里,但我无法获取这些参数。有没有办法从数据源对象中获取这些值。
最佳答案
转换为 DataSource
的具体实现 - tomcat 池数据源提供对 username
、url
等的访问(参见 DataSource详情):
if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) {
org.apache.tomcat.jdbc.pool.DataSource tcDataSource = (org.apache.tomcat.jdbc.pool.DataSource)dataSource;
logger.info(tcDataSource.getUrl());
logger.info(tcDataSource.getUsername());
...
}
关于java - 如何在java中使用数据源对象获取数据库配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661892/