2

I am trying to add some additional values into the i18n messageSource in Grails.

The default message.properties work fine but I need some additional values loaded from a remote resource (I know it is not good, but you know, managements... ).

I am trying to load these variables through the Boostrap.groovy example:

def messageSource = new StaticMessageSource()
messageSource.addMessage("key1", new Locale("en"), "English Value")
messageSource.addMessage("key2", new Locale("de"), "Other Language Value")

When I try to access them in any GSP via the

<g:message code="key1" /> 

only the key is returned, as if the values where not set at all at the StaticMessageSource. Apparently I am not having much luck with the documentation.

There is nothing on the Grails website and almost nothing on the SpringFramework. Will appreciate any suggestions.

Anyother way to add the a set of messages to the messageSource Session!?

4

2 回答 2

4

The messageSource bean is declared in Grails with the PluginAwareResourceBundleMessageSource class. When I need more funcionality in this, I create a grails plugin and configure the context to load my class intead of the Grails one.

Something like:

src/groovy/MyMessageSource.groovy

class MyMessageSource extends PluginAwareResourceBundleMessageSource {
  String getMessage(String key, Object[] args, Locale locale) {
    String message
    //handle your custom keys
    if(key.contains('myCoolMessagePrefix') {
    } else {
      //or delegate to the default of Grails
      message = super.getMessage(key, args, locale)
    }

    return message
  }
}

The plugin descriptor -> MyMessagesGrailsPlugin.groovy

def doWithSpring = { 
  //here we change the bean definition to use the customized messagesource
  def beanconf = springConfig.getBeanConfig('messageSource')
  def beandef = beanconf ? beanconf.beanDefinition : springConfig.getBeanDefinition('messageSource')

  if (beandef) {
    beandef.beanClassName = MyMessageSource.class.name
  }
}
于 2013-10-17T16:17:26.593 回答
2

I have solved a similar issue by following:

  1. set the custom message codes in grailsApplication.config (you can set where-ever you want as long as you can get to it from your custom MessageSource)
  2. extend the PluginAwareResourceBundleMessageSource
  3. override the resolveCode and resolveCodeWithArguments, to check your custom source
  4. use the "application" reference (its in the base class) to get to the config
  5. redefine the message source in resources.groovy:

messageSource(MyMessageSource) { bean -> bean.autowire = "byName" //-THIS IS IMPORTANT basenames = "WEB-INF/grails-app/i18n/messages" }

于 2013-10-18T03:39:00.543 回答