How to change Spring to use Datasource from Tomcat

2019-04-02 11:17发布

问题:

How to change Spring to use Datasource from Tomcat vs BasicDataSource? below is a copy of the bean I make in my XML. Can someone tell me how to access the tomcat datasource

<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:

In spring you have to change the configuration that it takes the configuration from tomcat via JNDI

<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>

Then you have to configure the connection within tomact and make it available though jndi. For example you could put this in the tomcat context.xml (and of course you need to put the driver in the tomcat lib directory)

<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" />