首页 > 解决方案 > 将 @RequestScoped Bean 注入 Runnable 类

问题描述

我在将@RequestScopedBean 注入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 注入错误......

标签: jakarta-eecdi

解决方案


我确信问题在于我的 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);

推荐阅读