有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在多个项目/模块中使用多个属性文件(通过PropertyPlaceHolderConfigure)

我们目前正在编写一个分为多个项目/模块的应用程序。例如,让我们以以下模块为例:

  • myApp DAO
  • myApp jabber

每个模块都有自己的Spring上下文xml文件。对于DAO模块,我有一个PropertyPlaceHolderConfigure,它读取带有必要的db连接参数的属性文件。在jabber模块中,我还有一个用于jabber连接属性的PropertyPlaceHolderConfigure

现在是主应用程序,包括myApp DAO和myApp jabber。它读取所有上下文文件并启动一个大的Spring上下文。不幸的是,似乎每个上下文只能有一个PropertyPlaceHolderConfigure,所以无论哪个模块首先加载,都能够读取它的连接参数。另一个抛出异常,错误为“无法解析占位符'jabber.host'”

我有点理解问题是什么,但我并不真正知道解决方案——或者我的用例的最佳实践

如何配置每个模块,使每个模块都能够加载自己的属性文件?现在,我已经将PropertyPlaceHolderConfigure从单独的上下文文件中移出,并将它们合并到主应用程序的上下文中(使用单个PropertyPlaceHolderConfigure加载所有属性文件)。但这很糟糕,因为现在每个使用dao模块的人都必须知道,他们的上下文中需要一个PropertyPlaceHolderConfigure。。dao模块中的集成测试也会失败等

我很想听听stackoverflow社区的解决方案/想法


共 (5) 个答案

  1. # 1 楼答案

    我尝试了下面的解决方案,它在我的机器上工作

    <context:property-placeholder location="classpath*:connection.properties" ignore-unresolvable="true" order="1" />
    
    <context:property-placeholder location="classpath*:general.properties" order="2"/>
    

    In case multiple elements are present in the Spring context, there are a few best practices that should be followed:

    the order attribute needs to be specified to fix the order in which these are processed by Spring all property placeholders minus the last one (highest order) should have ignore-unresolvable=”true” to allow the resolution mechanism to pass to others in the context without throwing an exception

    资料来源:http://www.baeldung.com/2012/02/06/properties-with-spring/

  2. # 2 楼答案

    我知道这是一个老问题,但ignore-unresolvable属性对我不起作用,我不知道为什么

    问题是我需要一个外部资源(比如location="file:${CATALINA_HOME}/conf/db-override.properties"),而ignore-unresolvable="true"在这种情况下不起作用

    忽略缺失的外部资源需要做的是:

    ignore-resource-not-found="true"
    

    以防万一有人碰到这件事

  3. # 3 楼答案

    ^{}bean有一个名为“propertiesArray”的替代属性。使用此属性而不是“properties”属性,并使用<array>个属性引用对其进行配置

  4. # 4 楼答案

    您可以有多个^{}元素,而不是显式声明多个PropertiesPlaceholderConfigurer bean

  5. # 5 楼答案

    如果您确保每个占位符在所涉及的每个上下文中都忽略了无法解析的键,那么这两种方法都有效。例如:

    <context:property-placeholder
    location="classpath:dao.properties,
              classpath:services.properties,
              classpath:user.properties"
    ignore-unresolvable="true"/>
    

    或者

        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath:dao.properties</value>
                    <value>classpath:services.properties</value>
                    <value>classpath:user.properties</value>
                </list>
            </property> 
            <property name="ignoreUnresolvablePlaceholders" value="true"/>
        </bean>