2015-10-05 76 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>