Spring开机。如何利用原型作用域?

Spring boot. How to take advantage of the Prototype scope?

我正在尝试找到一种在 Spring 引导中创建优雅的 Runnable bean 的方法。该应用程序的重点是拥有一项服务,该服务将接收一些数据并启动受监控的外部进程。

在我之前的尝试中,我只是形成了一个常规的 new MyRunnable() 并将其传递给执行服务。现在我正在考虑如何使用 Spring 环境正确地执行此操作,并使用 @Scope("prototype").

我确实找到了使用 ApplicationContext.getBean(...) 的示例,以及更好的 Why is Spring's ApplicationContext.getBean considered bad? 方法,但我仍然无法正确理解如何实际调用 new MyRunnable()服务,它将遵循以下简单的想法:

class MyService {
  public void triggerNewExternalTask() {
       ....
       executionService.run(new MyRunnable());

我相信你走错了路。

Spring 依赖注入很棒,但这并不意味着你 永远不会 在正确编写的 [=] 中找到对 new 的调用28=]启动应用程序。

在这种情况下,调用 new 是正确的做法。池中的每个 Executor 在启动时都应该有自己的 Runnable/Callable 实例。

对于任何方法范围的变量都是如此:最好在方法范围内实例化它,并让垃圾收集器在您退出方法时清理它。在这种情况下,Spring 没有理由对 bean 生命周期负责。

当您尝试共享 Runnable 个实例时,您做得太过分了,尤其是当它们具有状态时。

即使问题已关闭,也偶然发现了另一个解决方案,即-@Lookup,它满足了任务: 实体:

@Component
@Scope("prototype")
public class Proto {
    private static int counter;
    public Proto() {
        System.out.println("count: "+counter++);
    }
}

服务:

@Service
public class ProtoService {
    @Lookup
    public Proto getProto() {
        return null;
    }
}

和测试:

@Service
public class LookupWorks {
    @Autowired
    private ProtoService serv;

    @PostConstruct
    private void test() {
        System.out.println(">>>>>>>>>>>>>>");
        serv.getProto();
        serv.getProto();
        serv.getProto();
        serv.getProto();
        serv.getProto();
        System.out.println(">>>>>>>>>>>>>>");
    }


}

输出:

>>>>>>>>>>>>>>
count: 0
count: 1
count: 2
count: 3
count: 4
>>>>>>>>>>>>>>