Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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

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

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

Here is a reproducer :

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...