1

I did some experimentation with Quarkus and I am having difficulties understanding how @RequestScoped works. Coming from Spring, I would be expecting that the following code should not work and throw an Exception:

@ApplicationScoped
public class AppLifecycleBean {

    @Inject
    MyBean myBean;

    void onStart(@Observes StartupEvent ev) {
        myBean.doSomething();
    }
}

@RequestScoped
public class MyBean {
    public void doSomething() {
        System.out.println("Hello!");
    }
}

The request scoped bean is correctly injected as a proxy. But calling a method on the proxy even when there is no request available seems to work just fine?

Dave
  • 420
  • 1
  • 3
  • 14
  • 3
    It works just like you expect, the only thing you need to realize is that there's more notions of "request" than just HTTP request. In other words, the request context is activated on more occasions than just for processing an HTTP request. Quarkus specifically documents that the request context is activated for notifications of synchronous observers, which is the behavior you see: https://quarkus.io/guides/cdi-reference#request-context-lifecycle – Ladicek Jul 01 '22 at 17:23
  • Ok, that makes sense. Just out of curiosity: is there some overview where all those other types of requests that work with `@RequestScoped` are documented? I did not explicitely find something in the Quarkus documentation (except the one you already mentioned). I also discovered myself that `@Scheduled` method also seems to work with `@RequestScoped`. – Dave Jul 12 '22 at 18:36
  • I don't think there's a list, no. But in general, I think most Quarkus extensions activate the request context whenever they start a new independent "thread" of execution, because that is conceptually a request. Plus it's convenient to be able to use `@RequestScoped` beans [almost] anywhere. (Putting the word "thread" into quotes, because I'm not talking about `java.lang.Thread`, hope you see what I mean by that.) – Ladicek Jul 13 '22 at 07:20

1 Answers1

0

If a bean class has the annotation @RequestScoped, CDI will lazily instantiate the bean during the first call to a bean method. Such a bean lives only within a chain used to process a single HTTP request.

Overview of Bean Scopes in Quarkus

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83