从线程调用bean时,范围类型javax.enterprise.context.RequestScoped没有活动的上下文 [英] No active contexts for scope type javax.enterprise.context.RequestScoped when invoking a bean from a thread

查看:713
本文介绍了从线程调用bean时,范围类型javax.enterprise.context.RequestScoped没有活动的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Weld-SE 2.1.2.Final获取bean并从线程调用它时,我遇到以下异常:

While using Weld-SE 2.1.2.Final to obtain a bean and to invoke it from a thread, I encounter the following exception:


线程main中的异常org.jboss.weld.context.ContextNotActiveException:WELD-001303:范围类型javax.enterprise.context.RequestScoped没有活动的上下文

Exception in thread "main" org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped

我的bean用@RequestScooped注释。如果我注释@ApplicationScoped然后它工作正常,但我需要保留@RequestScooped。

My bean is annotated with @RequestScooped. If I annotate @ApplicationScoped then it works fine, but I need to keep @RequestScooped.

这是一个复制器:

public static void main(String[] args) throws Exception {
    Weld weld = new Weld();
    WeldContainer container = weld.initialize();
    final MyPojo pojo = container.instance().select(MyPojo.class).get();

    Thread t = new Thread() {
        public void run() {
            System.out.println(pojo.ping());   // This call fails
        }
    };
    t.start();
    t.join();
    System.out.println(pojo.ping()); // This call succeed
    weld.shutdown();

}

@RequestScoped
public class MyPojo {
 public String ping() {
    return "pong";
 }
}

您是否遇到过此行为?有什么想让这个工作吗?

Did you encounter this behavior? Any idea to make this work please?

推荐答案

在这种情况下,Weld正在使用与线程关联的未绑定RequestContext( RequestContext )。你需要在你正在创建的线程中手动初始化新的RequestContext,这对我有用:

In this case Weld is using unbound RequestContext that is associated with a thread (RequestContext). You need to manually initialize new RequestContext in a thread that You're creating, this works for me:

public static void main(String[] args) throws Exception {
    Weld weld = new Weld();
    final WeldContainer container = weld.initialize();
    RequestContext requestContext= container.instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get();
    requestContext.activate();

    final MyPojo pojo = container.instance().select(MyPojo.class).get();

    Thread t = new Thread() {
        public void run() {
            RequestContext requestContext= container.instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get();
            requestContext.activate();
            System.out.println("1" + pojo.ping()); 
        }
    };
    t.start();
    t.join();
    System.out.println("2" + pojo.ping());
    weld.shutdown();

}

这篇关于从线程调用bean时,范围类型javax.enterprise.context.RequestScoped没有活动的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆