【问题标题】:Bind values in property file dynamically using Spring使用 Spring 动态绑定属性文件中的值
【发布时间】:2014-05-26 12:05:21
【问题描述】:

在我的 web 应用程序中,我有一个场景,比如我需要从属性文件中读取值,并且必须在 spring bean 中动态更新该值。我创建的键值对如下,

message1=Hi {0} welcome. Your last signed in was {1}

如何替换 {0} 和 {1} 的值。我已经在 spring 中使用属性占位符配置器读取了该值。

【问题讨论】:

  • 不要读取配置了使用MessageSource<spring:message /> 标记的属性占位符的文件。

标签: spring


【解决方案1】:

你必须用MessageSource来做

在你的 applicationContext 添加:

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

在你的javacode中你可以写:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//...
String name = context.getMessage("message1", new Object[] { "user XY", "05.05.2010" }, Locale.US);

您甚至可以为不同的语言使用不同的 message.properties 文件:然后您必须将这些文件命名为:[filename]_[languageCode](即messages_en_US.propertiesmessages_de_DE.properties)。并更改 getMessage 方法的第三个参数。

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 2020-03-22
    • 1970-01-01
    • 2011-04-24
    • 2012-07-08
    • 2018-09-07
    • 2023-03-31
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多