【问题标题】:Spring datasources multiple profilesSpring数据源多个配置文件
【发布时间】:2014-10-14 11:49:34
【问题描述】:

我想为各种数据库创建配置文件,我可以根据我使用的数据库加载这些配置文件。

这是我的 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 容器。 我在配置文件上下文中的开发配置文件中包装应用程序上下文的方式可能做错了吗?

【问题讨论】:

    标签: java xml spring


    【解决方案1】:

    Spring 使用StringUtils. commaDelimitedListToStringArray 解析spring.profiles.active 的值。此方法不是非常宽容,并将您的个人资料字符串解析为{"dev", " mysql"} - 请注意mysql 之前的空格。

    param-value 元素中删除逗号后的空格,您的代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      相关资源
      最近更新 更多