如何唯一地命名对象

Raj*_*gan 5 java jdbc tomcat7 apache-commons-dbcp

我有一个简单的webapp,它从tomcat JDBC数据源获取连接.为了跟踪连接使用情况,我打算在打开和关闭连接时实现日志记录.记录应该打印这样的东西.

20151230143623.947[Thread-3] INFO  [DataSourceManager:19] Opened connection identified by id : BlahBlahBlah1
20151230143623.947[Thread-3] INFO  [DataSourceManager:19] Closed connection identified by id : BlahBlahBlah1
Run Code Online (Sandbox Code Playgroud)

我的开放和关闭方法是这样的.

Connection openConnection(String JNDILookupName) throws Exception {
    Connection connection = DataSourceManager.getConnection(JNDILookupName);
    logDBOperation("Opened", connection.toString());
    return connection;
}
Connection closeConnection(String JNDILookupName) throws Exception {
    connection.close();
    logDBOperation("Closed", connection.toString());
}
void logDBOperation(String operation, String connecitonName){
    logger.info(operation+" connection identified by id : "+connectionName);
}
Run Code Online (Sandbox Code Playgroud)

在这里,我使用Log connection.toString()作为Connection的唯一名称.但我想知道是否有更好的方法来做到这一点.

And*_*ert 2

只需使用超类的默认toString()实现即可Object

它已经为你做到了这一点:

getClass().getName() + '@' + Integer.toHexString(hashCode())
Run Code Online (Sandbox Code Playgroud)

它将toHexString(hashCode())为您提供唯一的 ID。这是 JVM 保证的,它将是一个唯一的值。