Luis Muñiz
Luis Muñiz

Reputation: 4811

How do you instantiate your own Validateable Object

I have a validateable object. When I instantiate it with new from an input Map, the ApplicationContext that should be embedded in the command object is not populated, and the invocaction fails when I call validate(), with the following Exception:

java.lang.IllegalStateException: Could not find ApplicationContext, configure Grails correctly first

What do I have to do to get a proper spring bean when I want to create a Validateable object and bind it to a Map of values?

Please note This code does not run in a grails controller: it runs in a rabbitMq consumer. So simple solutions applying to controllers will not work here.

class MyConsumer {
    static rabbitConfig = [
            queue    : 'myQueue'
    ]

    def handleMessage(Map message, MessageContext context) {
        def request = new MyValidateableRequest(message) //instantiates just a POGO
        if (request.validate()) { //Exception here
        //...
        } else {
        //...
        }
    }
 }

Upvotes: 0

Views: 85

Answers (1)

practical programmer
practical programmer

Reputation: 1648

It depends on Grails version and if you use plugin for RabitMQ. Normally consumer should be a spring bean and you can use code like below. grailsApplication is bean which should be injected into consumer

def object = new MyValidateableRequest()
//do request binding here
object.properties = [message: message]
AutowireCapableBeanFactory acbf = grailsApplication.mainContext.autowireCapableBeanFactory
acbf.autowireBeanProperties object, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false
object.validate()

If you are on Grails 3, example which will not require plugin https://spring.io/guides/gs/messaging-rabbitmq/ may be more interesting

Upvotes: 1

Related Questions