Spring JDBC와 DTO, DAO (3)

Minkyeong Kim·2021년 11월 25일
0

[boostcourse] Web-Backend

목록 보기
33/55

Config 설정해 DB 연결하기

1) config 패키지 생성하여 ApplicationConfig 클래스 작성

package kr.or.connect.daoexam.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({DBConfig.class}) //Config파일을 여러개로 나눠서 설정 가능
public class ApplicationConfig {

}
  • import를 사용하여 DBConfig 클래스의 Configuration을 가져옴

2) config 패키지 아래에 DBConfig 클래스 작성

package kr.or.connect.daoexam.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DBConfig {
	//DB관련 변수 설정
	private String driverClassName = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://localhost:3306/connectdb?userUnicode=true&characterEncoding=utf8&useSSL=false";
	private String username = "connectuser";
	private String password = "connect123!@#";
	]
	//Datasource를 통해 DB접속해야 함
	//Datasource 객체를 등록
	@Bean
	public DataSource dataSource(){
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
	}
	
}
  • DataSource를 Bean으로 등록하고, DB 정보들을 설정하여 반환
  • 주의할 점: javax.sql.DataSource를 import해야 함

3) main 패키지 생성하여 DataSourceTest 클래스 작성

package kr.or.connect.daoexam.main;
import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.sql.Connection;

import kr.or.connect.daoexam.config.ApplicationConfig;

public class DataSourceTest {
	public static void main(String[] args) {
		ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        // 컨테이너에서 DataSource 빈 가져옴
		DataSource ds = ac.getBean(DataSource.class);
		Connection conn = null;
		
		// DataSource 빈으로부터 커넥션을 잘 얻어와 연결되는지 확인
		try {
			conn = ds.getConnection();
			if (conn!=null) {
				System.out.println("접속 성공");
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(conn!=null) {
				try {
					conn.close();
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

0개의 댓글