Issue
Is it possible to have a bean definition that includes a Closure? At times, I've wanted to have nearly identical instances of a Class but differentiated in some small behavior - more than data so just passing different fields in my bean definitions is not enough.
Example desired bean definition:
beans {
myCustomWidget1(Widget) {
myClosure = { w -> return w.doThis() }
}
myCustomWidget2(Widget) {
myClosure = { w -> return w.doThat() }
}
}
Example class:
class Widget {
Closure myClosure
...
}
The problem is that Anonymous (Inner) Beans already uses a closure syntax and these anonymous beans are evaluated at application startup, instead of setting the class's Closure field. This obviously results in an exception at runtime.
I've overcome this previously be creating small helper classes that I inject into my bean, with the behavior changes being written as methods with the same name. I believe this is the correct approach but I was hoping for a more terse 'groovy' way.
We are using Grails 2.4.2 but I believe the BeanBuilder would treat my desired Closure as an anonymous bean, regardless of grails/groovy version.
Solution
One way to do it is instead of this...
beans {
myCustomWidget1(Widget) {
myClosure = { w -> return w.doThis() }
}
myCustomWidget2(Widget) {
myClosure = { w -> return w.doThat() }
}
}
Try this...
beans {
myCustomWidget1(Widget) { bean ->
bean.setPropertyValue 'myClosure', { w -> return w.doThis() }
}
myCustomWidget2(Widget) { bean ->
bean.setPropertyValue 'myClosure', { w -> return w.doThat() }
}
}
Answered By - Jeff Scott Brown