ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [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();
            }
        }
    }
Designed by Tistory.