Reading i18n messages from the database with Grails
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;
}
}
About Graeme Rocher
As Head of Grails Development for SpringSource, Graeme Rocher is the project lead and co-founder of the Grails web application framework. He's a member of the JSR-241 Expert Group which standardizes the Groovy language. Graeme authored the Definitive Guide to Grails for Apress and is a frequent speaker at JavaOne, JavaPolis, NoFluffJustStuff, JAOO, the Sun TechDays and more. Graeme joined SpringSource in late 2008 upon the acquisition of G2One Inc. Before founding G2One, Graeme was the CTO of SkillsMatter, a skills transfer company specializing in open source technology and agile software development, where Graeme was in charge of the company's courseware development strategy and general technical direction.
More About Graeme »NFJS, the Magazine
2011-06-01 00:00:00.0 Issue Now AvailableSpock: I Have Been, & Always Shall Be, Your Friendly Testing Framework
by Kenneth KousenWebSockets: Bidirectional Communication Over TCP
by Johnny WeyHigh Powered Messaging with RabbitMQ
by James CarrGORM: Object Persistence Done Right
by Dave Klein