【问题标题】:Create a new instance of component in Spring Boot/Framework在 Spring Boot/Framework 中创建组件的新实例
【发布时间】: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") 会在这里为您每次引用它创建一个 new bean 的技巧
  • 顺便说一句,我将@Controller 用于'TableProcessor'。 @Controller 和 @Bean 有什么区别?实际上,@Bean 在 IDE (IntelliJ) 中显示错误消息。

标签: spring spring-mvc dependency-injection spring-boot


【解决方案1】:

我遇到了类似的问题,我使用 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") 是一样的。

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多