2

I need to get the messageSource in a class in src\groovy. This class is used in UrlMappings.groovy, and at the stage I'm using this class the application is not completely started yet.

Currently I'm using the following and it works:

MessageSource messageSource = ApplicationHolder.application.mainContext.getBean('messageSource')
String message = messageSource.getMessage("code", null, "default", locale)

But the ApplicationHolder is deprecated, is there a way to achieve the same goal without using ApplicationHolder?

//I'm using Grails 2.0.1

2
  • The recommended way seems to be burtbeckwith.com/blog/?p=1017
    – Armand
    Jan 16, 2013 at 12:34
  • @Alison Thanks for the link, I've got it working with this. Could you post this as an answer?
    – BMH
    Jan 17, 2013 at 3:21

4 Answers 4

8

From my limited experience, I found that the simplest approach to get the messageSource in a POGO is simply:

Holders.applicationContext.getBean("messageSource")

The other approaches I tried (implementing MessageSourceAware or adding @Component/@Autowired annotations) caused other complications.

0
2

try this:

grails.util.GrailsWebUtil.currentApplication().mainContext.messageSource
1
  • add to class property: @Autowired protected ValidationTagLib validationTagLib and use as <g:message .../>
    – jenk
    Jan 17, 2013 at 10:44
1

The recommended way seems to be http://burtbeckwith.com/blog/?p=1017

I.e. create a singleton bean in src/groovy which implements ApplicationContextAware, and then configure it's factoryMethod attribute in grails-app/conf/spring/resources.groovy.

-1

I never like using Singletons which is what Holders, GrailsWebUtil, etc are doing. Instead you can just have grailsApplication injected in your service by doing:

class SomeService {
   def grailsApplication
   ...
}

Then use that to get a message rendered:

String message = grailsApplication.mainContext.getMessage(err, Locale.getDefault()).

Viola take any FieldError, ObjectError, or code and render a message from it.

1
  • Services are not living in src/groovy Oct 2, 2020 at 10:27

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.