【问题标题】:No active contexts for scope type javax.enterprise.context.RequestScoped when invoking a bean from a thread从线程调用 bean 时,范围类型 javax.enterprise.context.RequestScoped 没有活动上下文
【发布时间】:2014-12-25 04:49:42
【问题描述】:

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

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

我的 bean 用 @RequestScooped 注释。如果我注释@ApplicationScoped,那么它工作正常,但我需要保留@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";
 }
}

您是否遇到过这种行为?请问有什么想法可以完成这项工作吗?

【问题讨论】:

    标签: java multithreading cdi weld-se


    【解决方案1】:

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

    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();
    
    }
    

    【讨论】:

    • 它对我不起作用,除非我在创建线程之前复制请求上下文创建和激活。我相信您的答案的前一版本就是这种情况。
    • 太棒了!非常感谢您的帮助!
    • 对不起,我没有足够的声望来投票。我将答案标记为好答案。
    • 现在你也可以使用注解javax.enterprise.context.control.ActivateRequestContext
    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2013-05-06
    • 1970-01-01
    相关资源
    最近更新 更多