如何实例化自己的Validateable Object

时间:2015-12-25 19:35:20

标签: grails

我有一个可验证的对象。当我使用输入Map中的new实例化它时,不会填充应该嵌入在命令对象中的ApplicationContext,并且当我调用validate()时调用失败,具有以下异常:

  

java.lang.IllegalStateException:找不到ApplicationContext,首先正确配置Grails

当我想创建一个Validateable对象并将其绑定到值的Map时,我需要做些什么来获得一个合适的spring bean?

请注意此代码不在grails控制器中运行:它在rabbitMq使用者中运行。适用于控制器的简单解决方案在这里不起作用。

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 {
        //...
        }
    }
 }

1 个答案:

答案 0 :(得分:1)

这取决于Grails版本,如果你使用RabitMQ的插件。通常,消费者应该是一个spring bean,你可以使用如下代码。 grailsApplication是应该注入消费者的bean

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()

如果您使用的是Grails 3,那么不需要插件的示例 https://spring.io/guides/gs/messaging-rabbitmq/可能更有趣