【发布时间】:2015-07-02 03:37:10
【问题描述】:
在我基于 Spring Boot 的应用程序中,我有一个 @Component 类,其代码类似于:
ExecutorService executorService = Executors.newFixedThreadPool(poolSize);
// Start a separate thread for each entry
Map<Long, Future<Integer>> calls = new HashMap<>();
for (MyClass info : list) {
Callable<Integer> callable = new TableProcessor(info);
Future<Integer> future = executorService.submit(callable);
calls.put(info.getId(), future);
}
AutoWiring 在 TableProcessor 类中不起作用,因为(我认为)我正在使用“new”创建一个实例。 “为列表中的每个条目创建一个新实例”的最佳方法是什么?
注意:在这种情况下,将“Bean”添加到 Application 类中不起作用,因为我希望每个线程都有一个新实例。
【问题讨论】:
-
为什么它不起作用?只需添加一个 bean 使其原型作用域,每次您需要一个新实例时,在
ApplicationContext或BeanFactory实例上执行getBean。 -
M. Deinum - 对不起!对此有点新手。请提供示例代码。否则我会谷歌。但你的回答听起来很有希望。谢谢。
-
添加了这个:1)添加了'applicationContext'对象到这个类。 @Autowired ApplicationContext applicationContext; 2) 将“新”替换为:Callable
callable = applicationContext.getBean(TableProcessor.class); 3)在 TableProcessor 中添加了这个:@Scope("prototype") 似乎工作!这个好看吗? -
@DilTeam 如果它工作正常,一切都好,
@Scope("prototype")会在这里为您每次引用它创建一个newbean 的技巧 -
顺便说一句,我将@Controller 用于'TableProcessor'。 @Controller 和 @Bean 有什么区别?实际上,@Bean 在 IDE (IntelliJ) 中显示错误消息。
标签: spring spring-mvc dependency-injection spring-boot