【问题标题】: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,所以我们可以假设它不会占用资源。因此,无需使用尝试资源.

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2018-11-15
      • 2018-06-20
      • 2019-12-20
      • 2021-03-10
      • 2021-03-12
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多