No active contexts for scope type javax.enterprise.context.RequestScoped when invoking a bean from a thread

霸气de小男生 提交于 2019-11-29 09:24:05

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!