【问题标题】:Inject @RequestScoped Bean into Runnable class将 @RequestScoped Bean 注入 Runnable 类
【发布时间】:2020-01-03 10:58:59
【问题描述】:

我在将@RequestScoped Bean 注入Runnable 类时遇到问题。

这是我的资源类

@ApplicationScoped
@Path("/process")
public class TestResource {
    private static ExecutorService executor = Executors.newFixedThreadPool(20);

    @POST
    public void process(Integer id, @Suspended AsyncResponse ar) {
        TestRunnable testRunnable = new TestRunnable();
        testRunnable.setId(id);

        executor.execute(() -> {
            testRunnable.run();

            ar.resume("OK");
        });
    }

这是我的 TestRunnable 类:

public class TestRunnable implements Runnable {
    private Integer id;

    private ServiceBean serviceBean;

    public void asyncProcess() {
        serviceBean = CDI.current().select(ServiceBean.class).get();
        serviceBean.process(id);
    }

    @Override
    public void run() {
        asyncProcess();
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

当我尝试连接到端点时出现以下错误?

WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped

我确定问题出在我的 ServiceBean 注入错误...

【问题讨论】:

  • 如果您从语句testRunnable.run(); 中得到此异常并且您在相当新的应用程序服务器上运行,您可以尝试注入ManagedExecutorService,而不是创建自己的:@Resource ManagedExecutorService executor。其余代码保持不变。如果这对您有用,您甚至可以配置应用程序服务器以生成自定义的ManagedExecutorService(例如,具有 20 个线程)。

标签: jakarta-ee cdi


【解决方案1】:

我确定问题在于我的 ServiceBean 注入错误

不。问题正如异常消息所说:

No active contexts for scope type javax.enterprise.context.RequestScoped

根本没有可用的请求范围。

请求范围仅适用于在由 HTTP 请求创建的原始线程中运行的代码。但是您在这里基本上创建了一个新线程,该线程完全独​​立于(异步!)由 HTTP 请求创建的原始线程运行。

将请求范围中的所需数据作为构造函数参数传递。

TestRunnable testRunnable = new TestRunnable(serviceBean);

或者更好的是,将process() 逻辑移动到TestRunnable 本身。

TestRunnable testRunnable = new TestRunnable(id);

【讨论】:

  • 错误依旧...范围类型仍然没有活动上下文...
  • ServiceBean 中的某些内容可能仍在尝试通过 CDI 访问请求范围。最好遵循得墨忒耳定律:在传递给TestRunnable 之前将ServiceBean 转换为非托管POJO。 IE。创建一个新类并自己实例化它(使用new而不是CDI)并将感兴趣的信息复制到它(可能只有id变量和process方法背后的逻辑)然后让TestRunnable使用它而是。
猜你喜欢
  • 2014-06-02
  • 2016-06-08
  • 2019-08-04
  • 1970-01-01
  • 2015-07-14
  • 2016-04-06
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
相关资源
最近更新 更多