我想为各种数据库创建配置文件,我可以根据使用的数据库加载这些配置文件。
这是我的 application-context.xml 文件的相关部分:
<beans>
<!-- ...other beans in common profile-->
<beans profile="dev">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driverClassName}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<beans profile="mariadb">
<context:property-placeholder location="classpath*:databases/mariadb.properties"
ignore-unresolvable="true"/>
</beans>
<beans profile="mysql">
<context:property-placeholder location="classpath*:databases/mysql.properties"
ignore-unresolvable="true"/>
</beans>
<beans profile="hsql">
<context:property-placeholder location="classpath*:databases/hsql.properties"
ignore-unresolvable="true"/>
</beans>
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="${jndi.name}"/>
</beans>
我的dispatcher-servlet.xml
<beans>
<mvc:default-servlet-handler/>
<import resource="classpath*:profile-context.xml"/>
<mvc:annotation-driven/>
<beans/>
和 profile-context.xml
<beans>
<beans profile="dev">
<import resource="application-context.xml"/>
</beans>
<beans profile="production">
<import resource="application-context.xml"/>
</beans>
<beans/>
最后,我的 web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev, mysql</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
虽然这可以工作,但可以说使用 @ActiveProfile({"dev", "mysql"}) 进行 JUnit 测试,但它不适用于我的 Tomcat 容器。 我在配置文件上下文中的开发配置文件中包装应用程序上下文的方式是否可能做错了什么?
最佳答案
Spring 使用 StringUtils 解析
。此方法不是非常宽容,并将您的配置文件字符串解析为 spring.profiles.active
的值。 commaDelimitedListToStringArray{"dev", "mysql"}
– 请注意 mysql
之前的空格。
从 param-value
元素中删除逗号后的空格,您的代码应该可以正常工作。
关于java - Spring数据源多个配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26360103/