java - 您如何使用可以动态更改的spring指定数据源

标签 java spring spring-mvc jdbc

我正在开发一个应用程序,我需要根据情况指定不同的数据源。我想在测试应用程序时使用一个数据库,在生产环境中使用一个数据库。类似于通过属性文件或环境变量指定驱动程序类和登录详细信息。目前我必须更改详细信息然后重新启动应用程序。有没有办法在不重新启动应用程序的情况下动态更改这些属性?

最佳答案

使用 JNDI 数据源。

引用自 Spring in Action:

Spring applications will quite often be deployed to run within a JEE application server such as WebSphere, JBoss, or even a web container like Tomcat. These servers allow you to configure data sources to be retrieved via JNDI. The benefit of configuring data sources in this way is that they can be managed completely external to the application, leaving the application to simply ask for a data source when it’s ready to access the database. Moreover, data sources managed in an application server are often pooled for greater performance and can be hot-swapped by system administrators.

示例 applicationContext-dataSource.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jee="http://www.springframework.org/schema/jee"
   xsi:schemaLocation=" http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
      http://www.springframework.org/schema/jee 
      http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

   <!-- D A T A S O U R C E S -->
   <jee:jndi-lookup id="dataSource"
      jndi-name="jdbc/myDatasource"
      resource-ref="true" />
</beans>

希望这对您有所帮助。

关于java - 您如何使用可以动态更改的spring指定数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10777402/

相关文章:

java - Portlet session 中设置的属性在 Servlet session 中不可用

java - 从 java 类设置 jsp 中的属性列表

java - Spring不兼容的版本?

java - 获取自定义 Spring 作用域中的当前请求

json - 如何使用 Spring Hateoas 和 HAL 向链接添加附加属性?

java - 为什么我的变量包含 "2122"而不是 "2322"?

java - 如何使用 xsl FO 在 pdf 中打印数组

java - 数组到列表? Angular - Spring

java - Spring MVC 转换方法

java - 将数据插入数据库时​​无法 Autowiring 字段