我正在尝试使用maven pmd插件来检测整个项目中的所有连接泄漏。我们使用BaseSqlUtl.close关闭连接,所以如果我们可以使用PMD找到任何已打开连接的人使用此方法关闭,我们可以检测连接泄漏。 由于我们使用自定义类来关闭连接,因此我在以下ruleset.xml中创建了以**突出显示的规则集更改。
<?xml version="1.0"?>
<ruleset name="Design"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
The Design ruleset contains rules that flag suboptimal code implementations. Alternate approaches
are suggested.
</description>
<rule name="CloseResource"
since="1.2.2"
message="Ensure that resources like this {0} object are closed after use"
class="net.sourceforge.pmd.lang.java.rule.design.CloseResourceRule"
externalInfoUrl="http://pmd.sourceforge.net/pmd-5.0.5/rules/java/design.html#CloseResource">
<description>
Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.
</description>
<priority>3</priority>
<properties>
<property name="types" value="Connection,Statement,ResultSet"/>
**<property name="closeTargets" value="closeStatementQuietly,closeResultSetQuietly,commitAndCloseQuietly,rollbackAndCloseQuietly,closeQuietly,sqlUtil.closeQuietly,resetAndCloseQuietly"/>**
</properties>
<example>
<![CDATA[
public class Bar {
public void foo() {
Connection c = pool.getConnection();
try {
// do stuff
} catch (SQLException ex) {
// handle exception
} finally {
// oops, should close the connection using 'close'!
// c.close();
}
}
}
]]>
</example>
</rule>
</ruleset>
现在这适用于像commitAndCloseQuietly()这样的非参数化方法,但不幸的是,其他方法接受连接作为参数,如&#34; sqlUtil.closeQuietly(connection)&#34; 它给出了误报。
我尝试提到类似的问题但在这个具体情况下无法提供帮助: Identifying Connection not closed in java code using PMD
答案 0 :(得分:0)
PMD目前不支持使用帮助程序方法来关闭资源。即使可以配置close方法,也假定它们都在资源本身上被调用。
如果PMD做了多级DFA,可能会解决这个问题,而目前它并没有,而且可能也不会持续一段时间(它对缓存结果的能力有很大的影响)。
更好的解决方法是添加支持以指定将资源作为参数的紧密帮助方法。随意在Github上创建功能请求(https://github.com/pmd/pmd);甚至更好,提交公关。