2015-10-05 100 views
2

如何配置JNDI數據源中的Java配置文件,而不是在 「web.xml中」 Servlet上下文下面的代碼片段的:如何與Java配置配置JNDI的DataSource在Tomcat中8:

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

是在這裏回答:http://stackoverflow.com/questions/24941829/how-to-create-jndi-context-in-spring-boot-with-embedded-tomcat-container/26005740#26005740 – nekperu15739

+0

這裏回答:http: //stackoverflow.com/questions/24941829/how-to-create-jndi-context-in-spring-boot-with-embedded-tomcat-container/26005740#26005740 – nekperu15739

回答

7

注意:不要忘記在主安裝文件夾中將「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> 

二:在「Web應用程序」根文件夾類似下面的圖片創建META-INF文件夾和「context.xml的」文件:

enter image description here

三:添加下面的代碼片斷在 「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 
public DataSource dataSource() { 
    JndiDataSourceLookup dataSource = new JndiDataSourceLookup(); 
    dataSource.setResourceRef(true); 
    return dataSource.getDataSource("jdbc/DatabaseName"); 
} 

注:「JDBC /數據庫名稱」是「名」屬性,我們在「context.xml中」文件已經添加。

1

要完成衝鋒槍回答:對XML配置的春天,我用下面的代碼(注意「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>