Spring 2 JDBC datasource configuration

2019-06-25 09:45发布

问题:

I am currently looking at an application that uses Spring and Spring JDBC.

http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html

I can't find from the doc ways / where to configure settings such as set pool size, re-connection, test on borrow.

Am i missing something here? I am new to Spring. Is it that this plain vanilla JDBC option does not allow me to do what is described or is it that i would need something like c3po library?

回答1:

These properties are not part of Spring but underlying DataSource implementation. First you have to include some database pooling library like dbcp:

<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>

Once you added this library you configure the provided DataSource implementation:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="username" value="user" />
    <property name="password" value="pwd" />
    <property name="url" value="some:url" />
    <property name="driverClassName" value="some.class.Driver" />
    <property name="initialSize" value="5" />
    <property name="maxActive" value="10" />
    <property name="testOnBorrow" value="true" />
    <property name="validationQuery" value="SELECT 1" />
</bean>

You can also choose different DataSource implementations like c3p0. Finally you can obtain DataSource configured in your application server, e.g. using jndi. Spring JDBC support uses any DataSource implementation provided. Also Spring ships with some very simple DriverManagerDataSource intended for testing.



标签: spring jdbc