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})
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 {
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!@#";
]
@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 ds = ac.getBean(DataSource.class);
Connection conn = null;
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();
}
}
}
}
}