不管通过何种持久化技术,都必须通过数据连接访问数据库,在Spring中,数据连接是通过数据源获得的。在以往的应用中,数据源一般是 Web应用服务器提供的。在Spring中,你不但可以通过JNDI获取应用服务器的数据源,也可以直接在Spring容器中配置数据源,此外,你还可以 通过代码的方式创建一个数据源,以便进行无依赖的单元测试
配置JDBC数据源
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="test" />
<property name="password" value="123" />
</bean>
配置DBCP数据源连接池(commons-dbcp.jar,commons-pool.jar)
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="test" />
<property name="password" value="123" />
<property name="maxActive" value="80" />
<property name="maxIdle" value="20" />
<property name="maxWait" value="3000" />
</bean>
配置C3P0数据源连接池(c3p0.jar)
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass"
value="oracle.jdbc.driver.OracleDriver" />
<property name="jdbcUrl"
value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="user" value="test" />
<property name="password" value="123" />
<property name="acquireIncrement" value="5" />
<property name="idleConnectionTestPeriod" value="30" />
<property name="maxIdleTime" value="60" />
<property name="checkoutTimeout" value="3000" />
<property name="maxPoolSize" value="80" />
<property name="minPoolSize" value="5" />
<property name="maxStatements" value="6000" />
<property name="initialPoolSize" value="15" />
</bean>
C3P0在tomcat6 JNDI中配置
1.在tomcat6/conf 的context.xml文件中加入
<Resource name="jdbc/project"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
maxPoolSize="50" minPoolSize="2" acquireIncrement="2"
factory="org.apache.naming.factory.BeanFactory"
user="test" password="123"
driverClass="oracle.jdbc.driver.OracleDriver"
jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl" />
2.然后在spring的applicationContext.xml文件中加入
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/project" />
</bean>
或者为(注意要加上对应的jee命名空间声明)
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/project"/>