如题,此文是Grails的作者的一篇文章,无奈被墙,同时也为自己做个备份。 原文URL:http://graemerocher.blogspot.com/2010/04/reading-i18n-messages-from-database.html
In a recent consulting engagement, a client wanted to know how to go about reading i18n messages from the database rather than static properties files (the default in Grails). Considering how easy this is to do I was surprised when I Googled it that there was no information on how this is achieved.
class Message {
String code
Locale locale
String text
}
class DatabaseMessageSource extends AbstractMessageSource {
protected MessageFormat resolveCode(String code, Locale locale) {
Message msg = Message.findByCodeAndLocale(code, locale)
def format
if(msg) {
format = new MessageFormat(msg.text, msg.locale)
}
else {
format = new MessageFormat(code, locale )
}
return format;
}
}
beans = {
messageSource(DatabaseMessageSource)
}
@Immutable
class MessageKey implements Serializable {
String code
Locale locale
}
beans = {
messageCache(EhCacheFactoryBean) {
timeToLive = 500
// other cache properties
}
messageSource(DatabaseMessageSource) {
messageCache = messageCache
}
}
class DatabaseMessageSource extends AbstractMessageSource {
Ehcache messageCache
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
def key = new MessageKey(code,locale)
def format = messageCache.get(key)?.value
if(!format) {
Message msg = Message.findByCodeAndLocale(code, locale)
if(msg) {
format = new MessageFormat(msg.text, msg.locale)
}
else {
format = new MessageFormat(code, locale)
}
messageCache.put new Element(key, format)
return format
}
return format;
}
}