我试图弄清楚我的 Spring 应用程序如何确定它的部署位置并加载适当的数据源。我们有 3 个环境……我的本地、开发服务器和生产服务器。到目前为止,我有 3 个名为
的属性文件localhost.datasource.properties
development.datasource.properties
production.datasource.properties
我将它们配置如下:
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/resources/properties/production.datasource.properties</value>
<value>classpath:/resources/properties/development.datasource.properties</value>
<value>classpath:/resources/properties/localhost.datasource.properties</value>
</list>
</property>
</bean>
<bean id="dataSourceMySQL" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${mysql.jdbc.driver.class.name}"
p:url="${mysql.jdbc.url}"
p:username="${mysql.jdbc.username}"
p:password="${mysql.jdbc.password}" />
</beans>
当我在我的本地主机上时,这可以正常工作。如果我将 war 文件部署到开发中,它仍在读取 localhost 属性,因为它在列表中的最后一个,并且出现错误。实现这一点的最佳方法是什么?
谢谢
最佳答案
对于数据源,最简单的方法是定义数据源并让容器管理连接池。
为此,请在 web.xml 中定义对数据源的资源引用
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
并在 spring 中这样引用它:
<jee:jndi-lookup
id="dataSource"
jndi-name="jdbc/MyDataSource" />
然后您可以在应用服务器中定义数据源,这意味着您可以更改底层数据库。对于 websphere,这将通过 websphere 控制台完成。如果是 tomcat,它将通过 Context.xml 完成:
<Context>
...
<Resource name="jdbc/MyDataSource" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
这样您只需要更改上下文即可部署到开发、测试和生产中,而不必将您的应用程序绑定(bind)到特定的数据库。
关于java - 本地主机、开发和生产的 Spring 数据源配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7196311/