【问题标题】:Sonar issue: A "NullPointerException" could be thrown; "getDataSource()" can return null. How to solve in try with resources block声纳问题:可能会抛出“NullPointerException”; \"getDataSource()\" 可以返回 null。如何在尝试使用资源块时解决
【发布时间】:2022-08-03 21:47:51
【问题描述】:
这是使用资源块尝试的代码。
try (Connection con = jdbcTemplate.getDataSource().getConnection();
PreparedStatement preparedStatement = con.prepareStatement(sql);
Statement statement = con.createStatement()) {
....
}
标签:
java
exception
sonarqube
sonarqube-scan
underscore-java
【解决方案1】:
像这样:
DataSource ds = jdbcTemplate.getDataSource();
if (ds != null) {
try (Connection con = ds.getConnection();
PreparedStatement preparedStatement = con.prepareStatement(sql);
Statement statement = con.createStatement()) {
....
}
}
问题是DataSource 不是AutoClosable,所以我们可以假设它不会占用资源。因此,无需使用尝试资源.