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

时间:2015-04-23 18:59:50

标签: spring spring-mvc dependency-injection 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);
}

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

注意:在这种情况下,向Application类添加'Bean'是行不通的,因为我想为每个线程创建一个新实例。

1 个答案:

答案 0 :(得分:2)

我有类似的问题,我使用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(&#34; session&#34;)。但@Scope(&#34;原型&#34;)是一样的。

相关问题