【问题标题】:How to access to a property defined in messages.properties file?如何访问 messages.properties 文件中定义的属性?
【发布时间】:2011-01-04 14:03:19
【问题描述】:

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

作为测试,我尝试了以下语句:

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

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

欢迎任何帮助。

路易斯

【问题讨论】:

    标签: grails groovy properties internationalization multilingual


    【解决方案1】:

    要在 Groovy 中读取属性文件,您可以使用实用程序类 ConfigSlurper 并使用 GPath 表达式访问包含的属性。但是,您必须知道ConfigSlurper 不支持标准Java 属性文件。通常ConfigSlurper 将用于读取可能类似于属性文件但遵循标准groovy 表示法的.groovy 文件,因此字符串在引号内,而cmets 以// 开头或在/* */ 块内。因此,要读取 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"
    }
    

    【讨论】:

    • 感谢您的回答。您所做的对任何属性文件都有效,但消息是 i18n 文件。如果客户端的语言环境设置为其他语言,我认为这不会起作用。我的意思是,您没有阅读 message_de、message_es、message_fr 等。此外,所有消息都已被系统读取。如果可以避免的话,我不会再读它们了。
    • 只是从类路径加载的通知使用properties.load(getClass().getClassLoader().getResourceAsStream("message.properties"))
    • 在较新的 Java 版本中,toURL() 已弃用,只需执行以下操作:def config = new ConfigSlurper().parse(new File("message.groovy").toURI().toURL())
    【解决方案2】:

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

    message(code:"capacity.created")
    

    它有效!

    路易斯

    【讨论】:

    • 我有一个单独的类,它不是控制器,我试过了,但它不起作用......有什么建议吗?
    • @CPU100 将messageSource 注入该类并使用getMessage 方法。
    • 这对我有用,我必须为标题传递一个动态值:
    【解决方案3】:

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

    message(code:"capacity.created")
    

    在@Luixv 建议的控制器中或

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

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

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      相关资源
      最近更新 更多