Spring数据源多个配置文件

3

我想为不同的数据库创建配置文件,根据我使用的数据库进行加载。

以下是我的应用程序上下文文件中相关部分:

<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>

虽然这个方法可以在JUnit测试中使用@ActiveProfile({"dev", "mysql"}),但它无法在我的Tomcat容器中运行。也许是我在profile-context中的应用程序上下文包装方式有问题?

1个回答

1
Spring使用StringUtils.commaDelimitedListToStringArray解析spring.profiles.active的值。该方法不太容错,会将您的配置文件字符串解析为{"dev", " mysql"},请注意在mysql之前的空格。从param-value元素中删除逗号后面的空格,您的代码就可以正常工作了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接