关注 this blog article我使我的应用程序能够从数据库中加载 i18n 消息。它工作得很好。但是,我不想管理数据库中的所有消息。所以我想说如果我没有在数据库中找到代码,然后使用默认机制加载它。
这是我所拥有的:
class DatabaseMessageSource extends AbstractMessageSource {
protected MessageFormat resolveCode(String code, Locale locale) {
Message msg = Message.findByCodeAndLocale(code, locale)
def format = null
if (msg) {
format = new MessageFormat(msg.text, msg.locale)
}else{
// What do I do here to grab it from the file
}
return format;
}
}
我尝试调用 super.resolveCode(code, locale) 但这导致编译错误。而且我很难追踪 Grails 默认使用的 AbstractMessageSource 的实现来查看源代码。
更新:感谢 doelleri,我现在意识到我需要做的就是扩展 ResourceBundleMessageSource。不幸的是,这种方法存在几个问题。我的 resources.groovy 文件中有以下内容:
messageSource(DatabaseMessageSource)
首先,如果我只是扩展 ResourceBundleMessageSource 并覆盖 resolveCode 方法,则永远不会调用该方法。所以在我的 else block 中,调用 super.resolveCode 没有实际意义。
然后我尝试使用来自 ResourceBundleMessageSource 的所有代码来实现我的 DatabaseMessageSource 类,但我显然在 resources.groovy 中遗漏了一些东西,因为默认包没有连接起来。
所以在这一点上,我仍然不知道我需要做什么。我想先检查一下数据库。如果代码不存在,则恢复为与 ResourceBundleMessageSource 相同的默认行为。
最佳答案
我建议在新 bean 中保留一个 bundle-message-source 并将其注入(inject)您的 DatabaseMessageSource
.
资源.groovy:
// Place your Spring DSL code here
beans = {
messageSource(DatabaseMessageSource) {
messageBundleMessageSource = ref("messageBundleMessageSource")
}
messageBundleMessageSource(org.codehaus.groovy.grails.context.support.PluginAwareResourceBundleMessageSource) {
basenames = "WEB-INF/grails-app/i18n/messages"
}
}
DatabaseMessageSource.groovy:
class DatabaseMessageSource extends AbstractMessageSource {
def messageBundleMessageSource
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 = messageBundleMessageSource.resolveCode(code, locale)
}
return format;
}
}
这样,在备用解决方案中,将从相应的
messages_*.properties
中读取消息。文件,只需从一个资源包消息源请求它。请注意,您应该使用 PluginAwareResourceBundleMessageSource
,否则您可能会错过插件中的一些重要消息。
关于Grails i18n 来自数据库但默认返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100312/