jakarta-ee - 将 @RequestScoped Bean 注入 Runnable 类
问题描述
我在将@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 注入错误......
解决方案
我确信问题在于我的 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);
推荐阅读
- r - 在 Shiny 的单个 ObserveEvent 中删除和插入 UI 元素
- amazon-web-services - AWS ALB:侦听器规则找不到静态资源
- pine-script - 有没有办法在 tradingview pine 脚本中检测图表背景颜色?
- python - 如何为 python Copperhead 设置 MSVC++ 14.0 构建工具?
- laravel-5 - 我如何按日期分组?
- javascript - $.getJSON execution issue: json to array is populated but not used
- shell - 如何将文件名与makefile中的用户定义函数相关联
- android - 如何从 android studio 应用程序监听 mysql 数据库的任何更改?
- javascript - 默认情况下如何使第一个选项卡处于活动状态?
- javascript - 有没有办法通过双击不复制文本?