首页 文章

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

提问于
浏览
35

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

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

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

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

欢迎任何帮助 .

路易斯

3 回答

  • 2

    要在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"
    }
    
  • 70

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

    message(code:"capacity.created")
    

    它的工作原理!

    路易斯

  • 8

    对于i18n来说,阅读 message.properties 并不是最佳做法 . 您可以使用:

    message(code:"capacity.created")
    

    在控制器中@Luixv建议或

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

    在注入bean messageSource 之后的任何其他spring / grails bean中 .

相关问题