开发者

Multiple dependencies with Spring

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 c开发者_运维问答ase 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,


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>


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.


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>pechorin@hero.org</value>
    <value>raskolnikov@slums.org</value>
    <value>stavrogin@gov.org</value>
    <value>porfiry@gov.org</value>
</util:list>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜