How to avoid PMD CloseResource violation?

I am modifying my application code to comply with the pmd rules. I had a Close Resource error in this code:

Connection c = DataSourceUtils.getConnection(dataSource);
Statement request = null;
try {
    request = c.createStatement();
    request.execute(loadDataRequest);
} catch (SQLException e) {
    dataLogger.error(e);
    throw e;
}

So, I searched and found apache utility to avoid it: DButils My code became like this

Connection c = DataSourceUtils.getConnection(dataSource);
Statement request = null;
try {
    request = c.createStatement();
    request.execute(loadDataRequest);
} catch (SQLException e) {
    dataLogger.error(e);
    throw e;
} finally {
    DbUtils.closeQuietly(request);
    DbUtils.closeQuietly(c);            
}

However, I still have a PMD warning in eclipse and sonar reports! Do you have any ideas how to fix this forever?

+5
source share
3 answers

You can set closeTargetsthe PMD CloseResource rule property . When PMD finds similar method names, as in a property closeTargets, it does not light up with a warning message:

<properties>
    <property name="types" value="Connection,Statement,ResultSet"/>
    <property name="closeTargets" value="closeQuietly, closeConnection, close"/>
</properties>

Alternatively, you can use SourceMeter , which includes this configuration natively.

+2
source

, PMD , closeQuietly() . , close(), . Java, , Eclipse Sonar PMD, .

: 1) // NOPMD 2) , / , .

0

PMD defines a parameter for this rule called closeTargets. By default, this parameter is set to the method close. You can change it to indicateDbUtils.closeQuietly

0
source

All Articles