gaming3
gaming3

Reputation: 3

Inject @RequestScoped Bean into Runnable class

I have a problem with Injecting @RequestScoped Bean into Runnable class.

This is my Resource class

@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");
        });
    }

And here is my TestRunnable class:

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

When I try to connect to the endpoint I get the following error?

WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped

I am sure that the problem lies in wrong injection of my ServiceBean...

Upvotes: 0

Views: 894

Answers (1)

BalusC
BalusC

Reputation: 1108742

I am sure that the problem lies in wrong injection of my ServiceBean

Nope. The problem is exactly as the exception message says:

No active contexts for scope type javax.enterprise.context.RequestScoped

There is no request scope avaliable at all.

The request scope is only available to the code running within the original thread created by the HTTP request. But you're here basically creating a new thread which runs completely independently (asynchronously!) from the original thread created by the HTTP request.

Pass the desired data from the request scope as a constructor argument instead.

TestRunnable testRunnable = new TestRunnable(serviceBean);

Or even better, move the process() logic into TestRunnable itself.

TestRunnable testRunnable = new TestRunnable(id);

Upvotes: 1

Related Questions