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

问题描述 投票:35回答:3

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

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

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

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

欢迎任何帮助。

路易斯

grails groovy properties internationalization multilingual
3个回答
70
投票

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

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

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

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

与标准属性文件相比,这也提供了一些很好的优势,例如:代替

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

你可以写

capacity {
  created="x"
  modified="y"
}

8
投票

我找到了一种方法来直接访问消息属性,重新读取所有消息属性文件(message_de.properties,message_fr.properties等)这是非常容易的。

message(code:"capacity.created")

它的工作原理!

路易斯


2
投票

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

message(code:"capacity.created")

在控制器中@Luixv建议或

messageSource.getMessage("capacity.created",
                        [].toArray(), "Capacity Created.", null)

在注入豆子messageSource之后的任何其他春天/ grails豆。

© www.soinside.com 2019 - 2024. All rights reserved.