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