Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

grails - How to access to a property defined in messages.properties file?

I have a Groovy Grails application and I want to access programmatically to a property defined in messages.properties.

As a test, I've tried the following statement:

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

But it doesn't work (throws an exception).

Any help is welcomed.

Luis

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For reading property files in Groovy you can use the utility class ConfigSlurper and access the contained properties using GPath expressions. However, you have to be aware that ConfigSlurper doesn't support standard Java property files. Normally the ConfigSlurper will be used to read .groovy files that may be similar to a property file, but adhere to standard groovy notation, thus Strings are inside quotes and comments start with // or are inside a /* */ block. So, to read a Java properties file you need to create a java.util.Properties object and use that to create a 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

If you only use the property file from within Groovy code you should use the Groovy notation variant directly.

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

This also gives you some nice advantages over standard property files, e.g. instead of

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

you can write

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...