[英]How to Configure JNDI DataSource in Tomcat 8 with Java Configuration:
如何在Java配置文件中配置JNDI數據源而不是在“web.xml”Servlet上下文中跟隨代碼片段:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/DatabaseName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
注意:不要忘記將“mysql-connector-java-5.1.36.jar”復制到主安裝文件夾中的Tomcat的“lib”子文件夾中。
第一步:在“pom.xml”文件中添加以下依賴項:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
第二步:在“webapp”根文件夾中創建META-INF文件夾和“context.xml”文件,如下圖所示:
第三步:在“context.xml”文件中添加以下代碼片段:
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="DatabaseUsername" password="DatabasePasssword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/DatabaseName"/>
</Context>
第四:在Spring上下文配置文件中創建以下Bean:
@Bean
public DataSource dataSource() {
JndiDataSourceLookup dataSource = new JndiDataSourceLookup();
dataSource.setResourceRef(true);
return dataSource.getDataSource("jdbc/DatabaseName");
}
注意:“jdbc / DatabaseName”是我們在“context.xml”文件中已經添加的“name”屬性。
要完成SMG,請回答:對於xml配置的Spring,我使用以下代碼(請注意“webapp”配置文件,對於單元測試,您需要具有與Web服務器無關的數據源)
<beans profile="webapp">
<!-- get dataSources from web-container -->
<bean name="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:comp/env/jdbc/DatabaseName" />
<property name="resourceRef" value="true" />
</bean>
</beans>
它可以分3個步驟完成:
第1步:
在GlobalNamingResources標記下的tomcat conf / server.xml中添加以下條目。
<Resource auth="Container" driverClassName="DB_Drive_class-name" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/MyJNDI" password="&&&&&&&&&&&&&" type="javax.sql.DataSource" url="jdbc:db2://URL:PORT/DBNAME" username="&&&&&&&&&"/>
第2步:
在根上下文標記下的tomcat conf / context.xml中添加以下條目。
<ResourceLink name="jdbc/MyJNDI" global="jdbc/MyJNDI" type="javax.sql.DataSource"/>
第3步:
在web.xml中添加DataSource引用
<resource-ref>
<description>DB2 Datasource</description>
<res-ref-name>jdbc/MyJNDI</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
注意:這是一個全局Tomcat配置,DataSource可以與不同的應用程序共享。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.