Multiple Bean Instances in Spring

I was wondering if it is possible to specify x the sum of the same bean in the list in Spring. For example, instead of beans with identifiers: stage1, stage2, ... stageN, as here:

<bean id="stage1" class="Stageclass"/> <bean id="stage2" class="Stageclass"/> <bean id="stages" class="java.util.ArrayList"> <constructor-arg> <list> <ref bean="stage1" /> <ref bean="stage2" /> </list> </constructor-arg> </bean> 

Is it possible to do something like the following ?:

 <bean id="stage1" class="Stageclass"/> <bean id="stages" class="java.util.ArrayList"> <constructor-arg> <list> <ref bean="stage1" duplicate="20 times"/> </list> </constructor-arg> </bean> 

Thanks in advance.

+4
source share
3 answers

Entering the search method from http://static.springsource.org/spring/docs/2.5.x/reference/beans.html solved the problem. Just need to make sure that I need a bean with multiple instances with scope = "prototype"

+2
source

If you use an annotation-based configuration, and you specify a list of objects with the same interface as the dependency for any class, then spring will automatically scroll the wire automatically. Example:

 interface StageInterface { //... } class StageImpl1 implements StageInterface { //... } class StageImpl2 implements StageInterface { //... } @Component class StageContainer { private final List<StageInterface> stages; @Autowired public StageContainer(List<StageInterface> stages) { this.stages = stages; } public List<StageInterface> getStages() { return stages; } } 

This is spring version 3+.

I believe the same is possible with xml customization. In your case, it will probably be the same class (StageClass), but with different configuration options.

+3
source

You cannot do this using Spring's default default namespace. However, you can implement your own custom namespace in which you could support this syntax.

Alternatively, you can implement a static method that creates an ArrayList instance with duplicate elements.

+1
source

Source: https://habr.com/ru/post/1403776/


All Articles