-
[Java] try-with-resource 로 리팩토링Java/Spring 2025. 4. 28. 11:21
기존
public class DataSourceTest { public static void main(String[] args) { ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class); DataSource ds = ac.getBean(DataSource.class); Connection conn = null; try { conn = ds.getConnection(); if(conn != null) System.out.println("Connection Succeed"); } catch (Exception e) { e.printStackTrace(); } finally { if(conn != null) { try { conn.close(); }catch (Exception e) { e.printStackTrace(); } } } } }
리팩토링 후
package kr.or.connect.daoexam.main; import java.sql.Connection; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; import kr.or.connect.daoexam.config.ApplicationConfig; public class DataSourceTest { public static void main(String[] args) { ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class); DataSource ds = ac.getBean(DataSource.class); try (Connection conn = ds.getConnection()) { if (conn != null) { System.out.println("Connection Succeed"); } } catch (Exception e) { e.printStackTrace(); } } }
'Java > Spring' 카테고리의 다른 글
[Spring] WebMvcConfigurerAdapter 코드 WebMvcConfigurer 으로 리팩토링하기 (0) 2025.04.29