TLDR: I want my Spring Boot application to run some initialization code when it starts. The code needs access to Spring beans and values.
I'm writing a Spring Boot application that will consume multiple messages from a queue concurrently. In order to do this, it needs to instantiate multiple consumer objects. Does Spring have a good way to instantiate a configurable number of instances of the same class?
The queue client I have to use acts as a thread pool. It creates one thread for every consumer object I give it. The consumer objects only receive one message at a time, and they have to fully process and acknowledge the message before they can receive another one. The consumers aren't thread-safe, so I can't just use a singleton instance.
I considered the approach below, but it doesn't feel right to me. It seems like an abuse of the @Component
annotation because the Initializer
instance isn't used after it's constructed. What's a better way to do it?
@Component
public class Initializer {
public Initializer(ConsumerRegistry registry, @Value("${consumerCount}") int consumerCount) {
for (int i = 0; i < consumerCount; i++) {
// Each registered consumer results in a thread that consumes messages.
// Incoming messages will be delivered to any consumer thread that's not busy.
registry.registerConsumer(new Consumer());
}
}
}