Accessing i18n message in Grails service

Seems (to me) like an obvious need – referencing a translatable message in a service in a Grails app. But you can’t just use g:message – well, I’ve seen some workarounds that let you access the g namespace, but that doesn’t really seem advisable. I just want message handling. I found several references to the use of getMessage, e.g. this one on StackOverflow, but I had a little trouble implementing properly, so thought I’d make a note.

Requirements:

import org.springframework.context.MessageSource
def MessageSource messageSource

Then you can call getMessage, like this:

messageSource.getMessage("my.message.key", null, "default", myLocale)

Note two things: 1) null for args – I initially thought I could pass [] if I had no args, but that does not work, so pass null instead; and 2) myLocale – in my case I could probably just use Locale.default, but in keeping with the principle of il8n, I pass the locale as a variable into the service. So, in my controller I have (simplified):

import org.springframework.web.servlet.support.RequestContextUtils as RCU
class MyController {
  def myService
  def myAction() {
    myService.myMethod(RCU.getLocale(request))
  }
}

And in MyService I have (simplified):

import org.springframework.context.MessageSource
class MyService {
  def MessageSource messageSource
  def myMethod(Locale locale) {
    println messageSource.getMessage("message.key", null, "", locale)
  }
}

I know too that it is possible to get the locale from within the service via the application context, but that too seems ill advised if a way around it, so I’m trying to stick to the most “orthodox” approach I can come up with.

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *