How to do @Autowired on a List<Meucomponente>?

Asked

Viewed 27 times

0

Good morning,

I have a component that has injected services. This component is of the 'prototype' scope and is running infinitely. I need to run X components (passed via argument) of these and why I would like to use @Autowired List

But how to do this? How to exchange the 4 crawlers for a List?

@Component
@Scope("prototype")
public class Crawler implements Runnable {
    @Autowired private PaginaService service;
    @Autowired private StatusService statusService;
    
    @Override
    public void run() {
        // while loop infinito
    }
}
@Configuration
public class CrawlerExecutor {
    @Autowired private Crawler crawler1;
    @Autowired private Crawler crawler2;
    @Autowired private Crawler crawler3;
    @Autowired private Crawler crawler4;

    @Bean
    public TaskExecutor executor() {
        return new SimpleAsyncTaskExecutor();
    }
    
    @Bean
    public CommandLineRunner runner(TaskExecutor executor) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                executor.execute(crawler1);
                executor.execute(crawler2);
                executor.execute(crawler3);
                executor.execute(crawler4);
            }
        };
    }
}

Thanks!

1 answer

0


The only solution I could think of to this problem was to create a "qualified" Bean for the Crawlers list:

@Configuration
public class CrawlerList {

    @Autowired
    ApplicationContext context;

    @Value("${numberOfCrawlers}")
    private int number;

    @Bean
    @Qualifier("crawlers")
    public List<Crawler> crawlers() {
        List<Crawler> list = new ArrayList<>();
        for (int i = 0; i < number; i++) {          
            list.add((Crawler) context.getBean(Crawler.class));
        }
        return list;
    }
}

and change the Crawlerexecutor to inject this "qualified Bean":

@Configuration
public class CrawlerExecutor {
    
    @Autowired
    @Qualifier("crawlers")
    private List<Crawler> crawlers;

    @Bean
    public TaskExecutor executor() {
        return new SimpleAsyncTaskExecutor();
    }
    
    @Bean
    public CommandLineRunner runner(TaskExecutor executor) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                for (Crawler c : crawlers) {
                    executor.execute(c);
                }
            }
        };
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.