Grails i18n从数据库但默认返回文件

Gre*_*egg 11 grails internationalization

这篇博客文章之后,我启用了我的应用程序从数据库加载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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试调用super.resolveCode(代码,语言环境)但导致编译错误.而且我很难跟踪Grails正在使用的AbstractMessageSource的实现来查看源代码.

更新:感谢doelleri我现在意识到我需要做的是扩展ResourceBundleMessageSource.不幸的是,这种方法存在一些问题.我在resources.groovy文件中有以下内容:

messageSource(DatabaseMessageSource)
Run Code Online (Sandbox Code Playgroud)

首先,如果我只是扩展ResourceBundleMessageSource并覆盖resolveCode方法,那么永远不会调用该方法.所以在我的else块中,调用super.resolveCode是没有意义的.

然后我尝试使用ResourceBundleMessageSource中的所有代码实现我的DatabaseMessageSource类,但我显然在resources.groovy中遗漏了一些东西,因为默认的bundle没有连线.

所以在这一点上,我仍然迷失在我需要做的事情上.我想先检查数据库.如果代码不存在,则恢复为与ResourceBundleMessageSource相同的默认行为.

Chr*_*ris 12

我建议在一个新bean中保留一个bundle-message-source并将其注入到你的bean中DatabaseMessageSource.

resources.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"
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,在后备解决方案中,messages_*.properties只需从一个资源包消息源请求消息,就可以从适当的文件中读取消息.请注意,您应该使用PluginAwareResourceBundleMessageSource,否则您可能会错过插件中的一些重要消息.