spring配置JNDI数据源

准备工作:tomcat9+maven3+spring4

在spring配置JDNI数据源之前先了解下连接池、数据源、JNDI三者间的关系

连接池:
连接池是由容器(比如Tomcat)提供的,用来管理池中的连接对象。
连接池自动分配连接对象并对闲置的连接进行回收。
连接池中的连接对象是由数据源(DataSource)创建的。
连接池(Connection Pool)用来管理连接(Connection)对象。

数据源:
数据源(DataSource)用来连接数据库,创建连接(Connection)对象。
java.sql.DataSource接口负责建立与数据库的连接
由Tomcat提供,将连接保存在连接池中。

JNDI(Java Naming and Directory Interface,Java命名和目录接口):
在程序中使用JNDI获取数据源。

总结:通过数据源创建的连接对象被统一的放入到连接池中进行管理。

JNDI数据源属性解释:

<Resource name="jdbc/writeDS" 
auth="Container"  
type="javax.sql.DataSource" 
factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" 
maxActive="20" 
maxIdel="10" 
maxWait="1000" 
driverClassName="com.mysql.jdbc.Driver" 
username="root" 
password="12345" 
url="jdbc:mysql://192.168.22.76:3306/sums?characterEncoding=utf8&amp;generateSimpleParameterMetadata=true"/>

name:表示以后要查找的名称。通过此名称可以找到DataSource,此名称任意更换,但是程序中最终要查找的就是此名称.
auth:由容器进行授权及管理,指的用户名和密码是否可以在容器上生效
type:此名称所代表的类型,现在为javax.sql.DataSource
factory:指的是该Resource配置使用的是哪个数据源配置类,这里使用的是commons-dbcp.jar及其依赖的jar包,都放在tomcat的lib下
maxActive:表示一个数据库在此服务器上所能打开的最大连接数
maxIdle:表示一个数据库在此服务器上维持的最小连接数
maxWait:最大等待时间。10000毫秒
username:数据库连接的用户名
password:数据库连接的密码
driverClassName:数据库连接的驱动程序
url:数据库连接的地址

备注:tomcat版本不同则factory值不一样

tomcat7:或者tomcat8:factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"

tomcat9:factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"

spring配置JNDI数据源三种方式:

方法一:单个应用独享数据源

Tomcat的server.xml找到工程的Context节点,添加一个私有数据源

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
			   
		<!--JNDI配置数据源-->
		<Context docBase="sums-admin" path="/sums-admin" reloadable="true" source="org.eclipse.jst.jee.server:sums-admin">
		<Resource name="jdbc/writeDS"
		auth="Container"
		type="javax.sql.DataSource"
		factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
		maxActive="20"
		maxIdel="10"
		maxWait="1000"
		driverClassName="com.mysql.jdbc.Driver"
		username="root"
		password="12345"
		url="jdbc:mysql://192.168.22.76:3306/sums?characterEncoding=utf8&amp;generateSimpleParameterMetadata=true"/>
		</Context>		
      </Host>
    </Engine>
  </Service>
</Server>

总结:优点简单,缺点重用性差

方法二:配置全局JNDI数据源,应用到单个应用

第一步:在Tomcat的server.xmlGlobalNamingResources节点下加一个全局数据源

第二步:在Tomcat的server.xmlContext节点,增加对全局数据源的引用ResourceLink 

server.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
	
	<Resource name="jdbc/writeDS"
	auth="Container"
	type="javax.sql.DataSource"
	factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
	maxActive="20"
	maxIdel="10"
	maxWait="1000"
	driverClassName="com.mysql.jdbc.Driver"
	username="root"
	password="12345"
	url="jdbc:mysql://192.168.22.76:3306/sums?characterEncoding=utf8&amp;generateSimpleParameterMetadata=true"/>	
			  
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
			   
		<!--JNDI配置数据源-->
		<Context docBase="sums-admin" path="/sums-admin" reloadable="true" source="org.eclipse.jst.jee.server:sums-admin">
			<ResourceLink global="jdbc/writeDS" name="writeDS" type="javax.sql.DataSource" />  
		</Context>		
      </Host>
    </Engine>
  </Service>
</Server>

还有一种方式:在tomcat的context.xmlcontext节点引入Resource

context.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>


    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
    <Resource name="writeDS"
	auth="Container"
	type="javax.sql.DataSource"
	factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
	maxActive="20"
	maxIdel="10"
	maxWait="1000"
	driverClassName="com.mysql.jdbc.Driver"
	username="root"
	password="12345"
	url="jdbc:mysql://192.168.22.76:3306/sums?characterEncoding=utf8&amp;generateSimpleParameterMetadata=true"/>
</Context>

总结:优点:重用性,可控性 缺点:配置相对第三种方法要繁琐一点,每个工程都得配

方法三:配置全局JNDI数据源,应用到所有Tomcat下部署的应用

第一步:在Tomcat的server.xmlGlobalNamingResources节点下加一个全局数据源

第二步:在Tomcat的context.xmlContext节点下加一个ResourceLink节点对第一步配置的数据源进行引用

server.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
	
	<Resource name="jdbc/writeDS"
	auth="Container"
	type="javax.sql.DataSource"
	factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
	maxActive="20"
	maxIdel="10"
	maxWait="1000"
	driverClassName="com.mysql.jdbc.Driver"
	username="root"
	password="12345"
	url="jdbc:mysql://192.168.22.76:3306/sums?characterEncoding=utf8&amp;generateSimpleParameterMetadata=true"/>	
			  
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
			   
		<Context docBase="sums-admin" path="/sums-admin" reloadable="true" source="org.eclipse.jst.jee.server:sums-admin">
		</Context>		
      </Host>
    </Engine>
  </Service>
</Server>

context.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>


    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
	
	<ResourceLink global="jdbc/writeDS" name="writeDS" type="javax.sql.DataSource"/>
	
</Context>

总结:优点:重用性,一次性到位 缺点:没有可控性

spring配置文件引入JNDI数据源:

<!-- 配置数据库-->
    <jee:jndi-lookup id="readDataSource" jndi-name="writeDS"
                     proxy-interface="javax.sql.DataSource" lookup-on-startup="false"/>

总结:

ResourceLink中global的name与server.xml中GlobalNamingResources的Resource的name一致
ResourceLink中name与spring中applicationContext.xml中jndi-name的name一致
项目启动加载spring配置文件applicationContext.xml根据jndi-name的name找到context.xml文件中ResourceLink的name,
从而得到对应的global的名字,进而找到全局jndi数据源

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以通过配置JNDI数据源来连接数据库。具体步骤如下: 1. 在Tomcat的conf/server.xml文件中添加数据源配置,例如: ``` <Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" maxTotal="100" maxIdle="30" maxWaitMillis="10000" username="myuser" password="mypassword" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mydatabase"/> ``` 2. 在Spring Boot的application.properties文件中添加JNDI数据源配置,例如: ``` spring.datasource.jndi-name=java:comp/env/jdbc/myDataSource ``` 3. 在Spring Boot的启动类中添加注解@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}),排除自动配置数据源,例如: ``` @SpringBootApplication @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 这样就可以使用JNDI数据源连接数据库了。 ### 回答2: Spring Boot是一种快速开发Web应用程序的框架,并且集成了许多常用的框架和库,其自带的tomcat默认使用了DBCP(Apache Common DBCP)连接池框架作为数据源,但是实际项目存在多种数据源的需求,这时候我们就可以通过配置JNDI来实现多数据源配置JNDI(Java Naming and Directory Interface)是Java命名和目录接口,JNDI数据源就是将数据库的信息绑定到JNDI命名空间中,使Web应用程序可以访问并使用它们。Spring Boot可以使用JNDI数据源来连接各种数据库,只需要在应用程序的配置文件中添加如下配置: ```yaml spring: jndi: name: java:comp/env/jdbc/mydatasource ``` 此配置告诉Spring Boot去查找一个名为“java:comp/env/jdbc/mydatasource”的JNDI数据源并使用它。但是,我们还需要在Tomcat服务器中创建一个名为“jdbc/mydatasource”的JNDI数据源,并将其绑定到数据库上: 1. 打开Tomcat服务器的目录,找到server.xml文件,在GlobalNamingResources节点下添加如下内容: ```xml <Resource name="jdbc/mydatasource" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" username="root" password="password" maxTotal="20" maxIdle="10" maxWaitMillis="10000"/> ``` 其中,name属性指定了JNDI数据源的名称,url指定了JDBC连接URL,username和password是数据库的用户名和密码,其他属性是为连接池设置的。这里使用的是MySQL数据库作为例子。 2. 重启Tomcat服务器,应用程序将能够通过JNDI查找到配置数据源,并连接到数据库。 通过上述方法,我们就可以在Spring Boot应用程序中使用JNDI数据源了,同时也可以添加多个数据源,只需要按照上述步骤配置即可。 ### 回答3: SpringBoot是一个开箱即用的框架,可以轻松帮助我们快速搭建JavaWeb应用程序。而JNDI数据源配置则是在应用程序中连接数据库时必不可少的一步。在SpringBoot中,我们可以使用Tomcat-jdbc来实现JNDI数据源配置。 以下是具体的步骤: 1. 在maven中引入Tomcat-jdbc的依赖。 ``` <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>${tomcat-jdbc.version}</version> </dependency> ``` 2. 在application.properties文件中定义数据源配置信息。 ``` # tomcat datasource spring.datasource.jndi-name=jdbc/myDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=mysql spring.datasource.test-on-borrow=true spring.datasource.test-while-idle=true spring.datasource.validation-query=SELECT 1 ``` 这里我们通过配置spring.datasource.jndi-name=jdbc/myDataSource来指定数据源JNDI名称为“jdbc/myDataSource”。其他配置信息包括驱动程序类名、URL、用户名和密码等都与普通的数据源配置一致。 3. 在application.properties文件中定义JNDI配置信息。 ``` # JNDI datasource spring.jndi.enabled=true spring.jndi.name=jdbc/myDataSource ``` 这里我们通过配置spring.jndi.enabled=true和spring.jndi.name=jdbc/myDataSource来启用并指定JNDI配置信息。 4. 在Tomcat中配置数据源。 在应用程序部署到Tomcat中之后,我们还需要在Tomcat中配置数据源。我们可以在Tomcat的server.xml文件中添加以下配置: ``` <GlobalNamingResources> <Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" maxTotal="100" maxIdle="30" maxWaitMillis="10000" username="root" password="mysql" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test" validationQuery="SELECT 1" /> </GlobalNamingResources> ``` 这里我们通过添加Resource元素来定义数据源,其中name属性的值与application.properties文件中定义的JNDI名称相同。 至此,我们就成功地配置JNDI数据源。在应用程序中可以通过@Resource注解来引用它: ``` @Resource(lookup="java:comp/env/jdbc/myDataSource") private DataSource dataSource; ``` 除了Tomcat-jdbc,其他的JNDI数据源也可以使用相同的方法来配置。如果我们不想使用JNDI数据源,也可以直接在application.properties文件中配置普通的数据源

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值