问题
I would like to make use of the g.message() functionality in the toString method of my domain class, but the g.-namespace is not accessible by default.
I doubt that a import g.*
will do the trick.
I already know that I can use the messageSource
functionality, but it would be nicer to use the same syntax as in the views.
回答1:
You can use:
class MyDomain {
def someMethod() {
def g = ApplicationHolder.application.mainContext.getBean( 'org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib' )
return g.message(....)
}
}
or else you can get messageSource
directly: ApplicationHolder.application.mainContext.getBean('messageSource')
回答2:
Using g.render in a grails service has some hints how to use "g:" in a service. I have not tested this, but it should work mostly the same in domain classes, with one important exception: a domain class cannot use InitializingBean since it's not a bean residing in the application context.
来源:https://stackoverflow.com/questions/6908231/how-to-access-the-g-namespace-in-a-domain-class