DBCP
DBCP(DataBase Connection Pool)
의존성 설정
이 문서에서는 apache common dbcp를 사용할 것이기 때문에 pom.xml에 maven 저장소에서 apache dbcp2 를 검색한 결과를 추가한다.
pom.xml
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.7.0</version>
</dependency>데이터베이스 연결을 위해 필요한 의존성도 추가해야한다. JDBC 문서를 참고.
Spring Bean 등록
DataSource 설정
Apache Common DBCP를 이용하기 위해서는 DataSource를 org.apache.commons.dbcp2.BasicDataSource로 등록해야 한다.
src/main/webapp/WEB-INF/spring/root-context.xml
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
	<property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
	<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
	<property name="username" value="test"></property>
	<property name="password" value="test"></property>
	
	<property name="maxTotal" value="20"></property>
	<property name="maxIdle" value="10"></property>
	<property name="maxWaitMillis" value="3000"></property>
</bean>기존의 JDBC에서 설정한 DriverManagerDataSource와 비교하기 위해 코드를 살펴보면 다음과 같다.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
	<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
	<property name="username" value="test"></property>
	<property name="password" value="test"></property>
</bean>추가된 항목은 다음과 같다.
- maxTotal : 유지할 Connection Pool의 최대 크기 
- maxIdle : 유지할 Connection Pool 내부의 유휴 연결 개수 
- maxWaitMillis : Connection Pool의 모든 연결이 사용중일 때의 대기시간(ms) 
JdbcTemplate 설정
생성한 dataSource를 JdbcTemplate에 설정한다.
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<property name="dataSource" ref="dataSource"></property>
</bean>Test 수행
다른 코드들은 기존의 JDBC와 다르지 않기 때문에 select 구문만 수행하여 연결이 정상적으로 이루어지는지 확인한다.
src/test/java : com.hakademy.spring13.Test01
package com.hakademy.spring13;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {
	"file:src/main/webapp/WEB-INF/spring/root-context.xml",
	"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"
})
public class Test01 {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Test
	public void selectCount() {
		String sql = "select count(*) from student";
		int count = jdbcTemplate.queryForObject(sql, Integer.class);
		System.out.println("count = "+count);
	}
	
}Last updated