如何访问messages.properties文件中定义的属性?

时间:2010-01-13 10:33:20

标签: grails groovy properties internationalization multilingual

我有一个Groovy Grails应用程序,我想以编程方式访问messages.properties中定义的属性。

作为测试,我尝试了以下声明:

println "capacity.created: ${messages.properties['capacity.created']}"

但它不起作用(抛出异常)。

欢迎任何帮助。

路易斯

3 个答案:

答案 0 :(得分:70)

要在Groovy中读取属性文件,可以使用实用程序类ConfigSlurper并使用GPath表达式访问包含的属性。但是,您必须知道ConfigSlurper不支持标准Java属性文件。通常,ConfigSlurper将用于读取可能类似于属性文件的.groovy文件,但遵循标准的常规表示法,因此字符串在引号内,注释以//开头或位于{ {1}}阻止。因此,要读取Java属性文件,您需要创建一个/* */对象并使用它来创建java.util.Properties

ConfigSlurper

如果您只使用Groovy代码中的属性文件,则应直接使用Groovy表示法变体。

def props = new Properties()
new File("message.properties").withInputStream { 
  stream -> props.load(stream) 
}
// accessing the property from Properties object using Groovy's map notation
println "capacity.created=" + props["capacity.created"]

def config = new ConfigSlurper().parse(props)
// accessing the property from ConfigSlurper object using GPath expression
println "capacity.created=" + config.capacity.created

这也提供了一些优于标准属性文件的优点,例如:而不是

def config = new ConfigSlurper().parse(new File("message.groovy").toURL())

你可以写

capacity.created="x"
capacity.modified="y"

答案 1 :(得分:8)

我找到了一种直接访问消息属性的方法,而无需重新阅读所有内容 消息属性文件(message_de.properties,message_fr.properties等) 这很容易。

message(code:"capacity.created")

它有效!

路易斯

答案 2 :(得分:2)

为i18n阅读message.properties并非最佳做法。您可以使用:

message(code:"capacity.created")
控制器中的

@Luixv建议或

messageSource.getMessage("capacity.created",
                        [].toArray(), "Capacity Created.", null)
注入bean messageSource后,在任何其他spring / grails bean中