在我基于 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 类将不起作用,因为我希望每个线程都有一个新实例。
最佳答案
我有一个类似的问题,我使用 ApplicationContext 解决了它。
这是一个例子,因为我喜欢看代码而不是解释事情,所以也许它会帮助同船的人:
首先,这是我要为其创建新实例的 Spring 组件:
@Component
@Scope("prototype")
public class PopupWindow extends Window{
private String someVar;
@PostConstruct
public void init(){
//stuff
someVar="hi";
}
}
这是我想要这个 Spring 组件的 2 个实例的类:
@Component
@Scope("session")
public class MainWindow extends Window{
private PopupWindow popupWindow1;
private PopupWindow popupWindow2;
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void init(){
popupWindow1 = applicationContext.getBean(PopupWindow.class);
popupWindow2 = applicationContext.getBean(PopupWindow.class);
}
}
在我的特殊情况下,我使用 Vaadin + Spring,这些注释使用 Vaadin 版本,即 @SpringComponent 和 @UIScope 而不是 @Scope("session")。但是@Scope("prototype") 是一样的。
关于spring - 在 Spring Boot/Framework 中创建一个新的组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29832122/