Is it possible to autowire a list of components in Spring?

40 Views Asked by At

I am using Spring Boot (2.7.16).

I have a number of components (each one annotated as a @Component) that implement, say, a Task interface.

In my service, I want to auto wire a list of tasks, ideally in a specific sequence

@Autowired
// Ideally, sequence like
@Qualifier("firstTask"), @Qualifier("secondTask"), @Qualifier("thirdTask")
private List<Task> tasks;

So that I can then run them all at some point. For example, something like;

tasks.foreach(task -> { 
  task.run();
});

I am currently auto wiring them individually and instantiating the list explicitly.

@Autowired
@Qualifier("firstTask")
private Task firstTask;


@Autowired
@Qualifier("secondTask")
private Task secondTask;

@Autowired
@Qualifier("thirdTask")
private Task thirdTask;

private List<Task> tasks = List.of(firstTask, secondTask, thirdTask);

But being able to auto wire the list directly would be fantastic.

1

There are 1 best solutions below

0
Vihung On BEST ANSWER

(I wrote the original question)

You can @Autowired a list of components

@Autowired
private List<Task> tasks;

will work.

However, if you want to define the sequence, you cannot do so in the service. You need to apply the @Order annotation on each component (this seems to me to be the wrong way round, but that's how it is done).

So,

@Component
@Order(1)
public class FirstTask implements Task {
  // ...
}

,

@Component
@Order(2)
public class SecondTask implements Task {
  // ...
}

, and

@Component
@Order(3)
public class ThirdTask implements Task {
  // ...
}