by

Creating List of Beans in Spring

Let’s think we need a list of IMoveable in a class and I need to pass it through property injection in Spring. The easiest way is:

It seems fine if you have a few items and new items won’t be added. What if you have more items (eg 100)? What if another developer add pyramidMoveableObject and forget to add it into moveableObjectList?

In these scenarios, we have prettier way to do it. I a class to find all beans which implements IMoveable interfaces, more generally find beans of given types.

I’ll use 2 interface in my class

  1. FactoryBean inteface of Spring, to create list of items
  2. ApplicationContextAware interface to access beans in my context.
Then we can create our IMoveable list through the following beans:
At the end, our scene bean looks like this: