【问题标题】:Read all properties files in a directory读取目录中的所有属性文件
【发布时间】:2014-01-11 01:20:48
【问题描述】:

现在我在 spring 中读取属性文件

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="customer/messages" />
</bean>

这里我指定读取客户目录中的messages.properties。但我想要做的是指定一个目录并要求 spring 读取该目录中存在的所有属性文件。我怎样才能做到这一点?

我尝试了 value="customer/*" 但它不起作用。

【问题讨论】:

    标签: java spring properties-file


    【解决方案1】:

    更推荐使用&lt;context:property-placeholder&gt;

    <context:property-placeholder 
        locations="classpath:path/to/customer/*.properties" />
    

    您也可以使用 Spring 3.1+ Java Config 来做到这一点:

    @Bean
    public static PropertyPlaceholderConfigurer properties(){
      PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
      Resource[] resources = new ClassPathResource[ ]
        { new ClassPathResource( "path/to/customer/*.properties" ) };
      ppc.setLocations( resources );
      ppc.setIgnoreUnresolvablePlaceholders( true );
      return ppc;
    }
    

    您可能需要定制资源类型以从以下位置加载属性:

    要使用属性,您可以使用Environment 抽象。它可以被注入并用于在运行时检索属性值。

    【讨论】:

    • 感谢您的回答...但是这个解决方案的问题是我必须编写一个实用程序类来读取属性。那么如何在运行时获取属性的值呢?
    • 使用 ResourceBundleMessageSource,我能够注入 messageSource 对象,它可以帮助我获取所有属性的值...
    • 在最后的参考资料中,有一节介绍了如何使用此类加载的属性。此外,请注意注解 @Bean 是 Java Config 方法的替代 XML 配置,它不是实用程序类。
    • 我也更新了答案。您可以使用 Environment 抽象,它具有解析和获取属性值的方法。如果您需要列出所有属性名称,那就另当别论了。
    • 感谢您的宝贵建议。但我最终使用了下面提到的另一种方法。
    【解决方案2】:

    【讨论】:

    猜你喜欢
    • 2013-12-02
    • 2012-06-13
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多