Defining a bean by calling function on another bean

10 / Dec / 2014 by Sachin 1 comments

In Grails, We can define custom beans in resources.groovy. A simple bean definition looks like

myClass(MyClass)

Read more about them here.

Recently, I wanted to define a bean, where the bean’s constructor required me to call a method on another bean to be instantiated.

To make it more clear, Let us consider a class A which has a method getApi() in it. Consider another class B, now to define class B as a spring bean we need to call getApi() method of class A (which itself is a spring bean) in the constructor of B.

In code the dependency is like this

A a = new A()
B b = new B(a.getApi())

The only complication being both A and B needed to be spring defined singleton beans in resources.groovy.

Lets see how we can solve this problem, In resources.groovy

a(A)
b(B) { beanDefinition ->
        beanDefinition.constructorArgs = ["#{a.getApi()}"]
}

In the above code, we defined the constructor arguments for class B, as a list containing only 1 element, which is a method invoked on bean “a”.

Now to use these 2 beans in a third class “C” is trivial, in resources.groovy just do


c(C) {
  a = ref("a")
  b = ref("b")
}

~~Cheers~~

Sachin Anand
sachin[at]intelligrape[dot]com
@babasachinanand

FOUND THIS USEFUL? SHARE IT

comments (1 “Defining a bean by calling function on another bean”)

  1. Roni

    Very nice blog :)

    You can also pass arguments to the bean’s constructor by passing more arguments to the bean definition as a varargs list. For eg:
    a(A)
    b(B, a.getApi())

    This can be used for as many arguments as the bean’s constructor takes.

    Reply

Leave a comment -