在 Spring Boot/Framework 中创建一个新的组件实例

Dil*_*eam 5 spring dependency-injection spring-mvc spring-boot

在我基于 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);
}
Run Code Online (Sandbox Code Playgroud)

AutoWiring 在 TableProcessor 类中不起作用,因为(我认为)我正在使用“new”创建一个实例。“为列表中的每个条目创建一个新实例”的最佳方法是什么?

注意:在这种情况下,将“Bean”添加到 Application 类将不起作用,因为我想要每个线程都有一个新实例。

Arm*_*rea 7

我有一个类似的问题,我使用 ApplicationContext 解决了它。

这是一个例子,因为我喜欢查看代码而不是解释事物,所以也许它会对同样情况的人有所帮助:

首先,这是我想要创建新实例的 Spring 组件:

@Component
@Scope("prototype")
public class PopupWindow extends Window{

    private String someVar;

        @PostConstruct
        public void init(){
          //stuff
          someVar="hi";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我想要这个 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的特定情况下,我使用 Vaadin + Spring,并且这些注释使用 Vaadin 版本,即 @SpringComponent 和 @UIScope 而不是 @Scope("session")。但 @Scope("prototype") 是相同的。