Spring_AutoCloseable

song·2023년 11월 2일

Spring

목록 보기
14/19

리소스 반납 한번에 하기

  • 아래와 같이 메소드를 따로 만들어서 실행시키기.
    close(pstmt, conn);
    close(rs, pstmt, conn);
    private void close(AutoCloseable... acs){
      for(AutoCloseable ac : acs){
        try{
          if(ac != null) ac.close();
        }catch(Exception e){
          throw new RuntimeException(e);
        }
      }
    }
    ... : 가변인자. 매개변수로 몇개가 들어올 진 모르겠지만 그 속성들을 배열처럼 받아서 저장

try catch resources

  • finally 가 없음.
  • 알아서 try() 영역 안에 있는 속성들을 사용이 끝나면 알아서 close 해줌
  • 그래서 () 영역 안에는 무조건 AutoCloseable 한 애들만 들어올 수 있음.
    • Connection, PreparedStatement, ResultSet
String sql = "select * from ?";
try(
  Connection conn = ds.getConnection();
  PreparedStatement pstmt = conn.prepareStatement(sql);
){
  pstmt.setString(1, "db");
}catch{
  throw new RuntimeException(e);
}
profile
계속 나아가기

0개의 댓글