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

标签 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”创建一个实例。 “为列表中的每个条目创建一个新实例”的最佳方法是什么?

注意:在这种情况下,将“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/

相关文章:

spring - 服务器返回 HTTP 响应代码 : 400 using Spring-Security AuthenticationProvider

java - Spring存储库中的Cassandra计数器数据类型操作

java - 在 Spring 中解析 Multipart/mixed

java - Spring MVC为什么此Hello World在没有注释驱动标签的情况下运行良好(与Spring的任何其他项目不同)

asp.net - 使用自定义成员资格提供程序进行依赖注入(inject)

java - 没有数据源的 Spring Boot + Spring Batch

spring-mvc - Spring : Get Registered URL Pattern in Controller from HttpRequest

java - 如何在没有部署描述符的情况下在 Spring 中注册监听器

java - 为什么Spring依赖注入(inject)有init-method?

java - Guice - 在构造函数内部使用注入(inject)字段