728x90
반응형
#메이븐(Maven) 기반 Spring 프로젝트 생성(오라클(Oracle) + 커넥션 풀(HikariCP)) 연결 및 설정 하는 방법
1. pom.xml에 HikariCP + spring junit 테스트용 라이브러리를 추가합니다.
<!-- HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.5</version>
</dependency>
<!-- Spring Junit -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
2. DataSourceConfig 클래스를 생성합니다.
package com.spring.web.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource(){
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName("oracle.jdbc.driver.OracleDriver");
hikariConfig.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:XE");
hikariConfig.setUsername("book_ex");
hikariConfig.setPassword("book_ex");
HikariDataSource dataSource = new HikariDataSource(hikariConfig);
return dataSource;
}
}
3. WebConfig 클래스에 DataSourceConfig.class 를 추가합니다.
package com.spring.web.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
// web.xml 대체 클래스
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class, DataSourceConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ServletConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
4. HikariCP 테스트
package com.spring.web.test;
import static org.junit.Assert.*;
import java.sql.Connection;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.spring.web.config.DataSourceConfig;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
@Slf4j
public class DataSourceTest {
@Setter(onMethod_ = { @Autowired })
private DataSource dataSource;
@Test
public void testHikaricpConnect(){
try(Connection con = dataSource.getConnection()) {
log.info("con= " + con);
} catch (Exception e) {
fail(e.getMessage());
}
}
}
5. 컨트롤키 + F11를 눌러서 JUnit Test 실행 후 연결을 확인합니다.
728x90
반응형
댓글