Grails i18n来自DB备份的属性文件?

Mar*_*rco 2 grails internationalization

我试图得到一个情况,我可以使用i18n属性文件备份数据库?

所以对于一些标准的东西,我想使用属性文件,但有些字段必须是最终用户可编辑的,所以我打算在数据库中使用i18n.所以真正的组合会很棒.如果在属性文件中找不到i18n代码,则在DB中进行查找.

知道如何解决这个问题吗?我已经看过Grails i18n从数据库发布但默认返回文件

但问题没有真正的答案,还有其他任何关于如何解决这个问题的建议?

Chr*_*ris 5

将新域类放入项目中:

class Message {
    String code
    Locale locale
    String text
}
Run Code Online (Sandbox Code Playgroud)

将以下行添加到您的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)

并将以下类添加到您的src/groovy文件夹:

class DatabaseMessageSource extends AbstractMessageSource {

    def messageBundleMessageSource

    protected MessageFormat resolveCode(String code, Locale locale) {
         Message msg = messageBundleMessageSource.resolveCode(code, locale)
         def format
         if(msg) {
             format = new MessageFormat(msg.text, msg.locale)
         }
         else {
             format = Message.findByCodeAndLocale(code, locale)
         }
         return format;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在grails将尝试解析消息包中的消息.如果它不可用,它将从数据库中查找.您可以添加一些错误处理,但如果所有消息至少在一个地方可用,则此版本有效.

有关更多详细信息,请参阅http://graemerocher.blogspot.com/2010/04/reading-i18n-messages-from-database.html.


有关更改的一些细节resources.groovy:

在此文件中,您可以定义可注入的groovy类,只需定义一个与其中定义的名称相同的变量即可resources.groovy.例如,在此文件中,有messageSourcemessageBundleMessageSource,您可以包含在任何控制器或服务文件中.如果定义了此变量,则会创建括号中的类的实例.

在这种情况下,我们会覆盖常规messageSource以使用我们的自定义实现DatabaseMessageSource.因此I18n功能message现在将使用我们的自定义实现.

由于我们的自定义实现需要检查message.properties-files,因此我们将原始消息源保留在第二个bean中.通过在我们的自定义实现中定义此实例,我们仍然可以使用旧的实现(因此以常规方式查找消息).