如何更改Spring以使用Tomcat与BasicDataSource的Datasource?

时间:2012-03-23 14:36:52

标签: spring jdbc tomcat6 spring-jdbc

如何更改Spring以使用Tomcat与BasicDataSource的数据源?下面是我在XML中创建的bean的副本。有人可以告诉我如何访问tomcat数据源

<beans:bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" >

        <beans:property
            name="driverClassName"
            value="${database.driver}" />

        <beans:property
            name="url"
            value="${database.url}" />

        <beans:property
            name="username"
            value="${database.user}" />

        <beans:property
            name="password"
            value="${database.password}" />

        <beans:property
            name="initialSize"
            value="5" />

        <beans:property
            name="maxActive"
            value="10" />
    </beans:bean>

1 个答案:

答案 0 :(得分:2)

在Spring中,您必须通过JNDI

更改从tomcat进行配置的配置
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myNewDatasource" />

</beans>

然后你必须在tomact中配置连接并通过jndi使其可用。 例如,您可以将它放在tomcat context.xml中(当然您需要将驱动程序放在tomcat lib目录中)

<Resource name="jdbc/myNewDatasource"
            type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://SERVER:3306/DB?useUnicode=true&amp;characterEncoding=utf8"

     auth="Container" username="USERNAME" password="PASSWORD"
     maxIdle="3" maxActive="15" maxWait="10000"
     logAbandoned="true" removeAbandoned="true" removeAbandonedTimeout="60"
     validationQuery="select 1" />