0

Can anyone advice me how can I inject multiple dependencies for a same bean in the spring framework? I will try to explain the scenario very briefly, in case anyone can suggest me a better solution.

I have a data repository and it has to go through certain filters to filter out unwanted data. The criteria for filtering change and are not fixed to one filter. So, I created a filter handler which filters data based on filters. I want to use IoC and inject the filter dependencies. Its straight forward till here, only that there can be multiple filters. How do I inject multiple dependencies. If I can create a List of filters, how do I declare a list in the xml file?

Thanks in advance,

0

3 Answers 3

3

You can do it like this (filter1 and filter2 are ids of beans defined elsewhere):

<property name="propertyName">
  <list>
    <ref bean="filter1"/>
    <ref bean="filter2"/>
  </list>
</property>
Sign up to request clarification or add additional context in comments.

Comments

2

If your filters all implement the same interface, the most elegant way (in my opinion) is like this:

@Autowired
private List<YourFilterInterface> filters;

This will wire a list containing all registered beans implementing YourFilterInterface. It's available in Spring version 2.5 and up.

Comments

1

The Spring docs tell you how to create a list.

Example taken from above link...

<!-- creates a java.util.List instance with the supplied values -->
<util:list id="emails">
    <value>[email protected]</value>
    <value>[email protected]</value>
    <value>[email protected]</value>
    <value>[email protected]</value>
</util:list>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.