Search code examples
grailsgrails-controller

Grails Command object @PostConstruct or something?


I want to initialize Command field from an injected Service.

So I need to execute a Command's method after it has been fully initialized, but before params is assigned to fields.

How can I do it? OK, I can get a Service bean by hand in constructor. Any better way?

Had no luck with @PostConstruct or InitializingBean - looks like Command is not a bean, right?

Grails 1.3.5


Solution

  • You're right the command is not a bean. You could instantiate the command instance by a service method and do initialization there and return the instance back to the controller. Than call the controller's bindData with the returned instance like this:

    // controller code
    def myService // injected
    
    def action = {
        def command = mySerivce.createCommandInstance() 
        bindData(command, params)
    }
    
    // service code
    class MyService {
        def createCommandInstance() {
           def cmd = new MyCommand()
           doSomeInitializationWithCommand(cmd)
           return cmd
        }
    }