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;
}
}