Spring框架中获得DataSource对象的方法

来源:http://www.oschina.net/code/snippet_117958_4699

在Spring框架中有如下3种获得DataSource对象的方法:

1.从JNDI获得DataSource.

2.从第三方的连接池获得DataSource.

3.使用DriverManagerDataSource获得DataSource.

JNDI方式
1、SpringJNDI数据源配置信息:
  <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
   <property name="jndiName">
    <value>java:comp/env/jcptDataSourceJNDI</value>
   </property>
  </bean>
  jcptDataSourceJNDI是tomcat或者其他应用服务器配置的JNDI.
 
2、关于JNDI的配置(tomcat):
  修改tomcat目录conf/context.xml文件:
  <Resource name="jcptDataSourceJNDI" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10"   username="tysp"
      password="12345678" driverClassName="oracle.jdbc.driver.OracleDriver"
      url="jdbc:oracle:thin:@192.168.1.35:1521:orcl"/> 
 
3、通过JNDI获取DataSource:
  Context context = new InitialContext();
  DataSource ds = (DataSource)context.lookup("java:comp/env/jcptDataSourceJNDI");

使用DBCP连接池获取

要在Spring中使用DBCP连接池,需要引入commons-collections.jar、commons-dbcp.jar和commons-pool.jar。
 
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="url" value="jdbc:oracle:thin:@192.168.1.35:1521:orcl"></property>
        <property name="username" value="or_meal"></property>
        <property name="password" value="or_meal"></property>
        <property name="maxActive" value="100"></property>
        <property name="maxIdle" value="30"></property>
        <property name="maxWait" value="10"></property>
        <property name="defaultAutoCommit" value="false"></property>
    </bean>
 
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
 
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect
                </prop>
                <prop key="show_sql">true</prop>
                <prop key="format_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources">
        <list></list>
        </property>
    </bean>

使用DriverManagerDataSource

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>oracle.jdbc.driver.OracleDriver
            </value>
        </property>
        <property name="url">
            <value>jdbc:oracle:thin:@192.168.1.35:orcl
            </value>
        </property>
        <property name="username">
            <value>or_meal</value>
        </property>
        <property name="password">
            <value>or_meal</value>
        </property>
    </bean>

相关推荐