How does RequestScope in Quarkus/CDI work?

3.4k Views Asked by At

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?

1

There are 1 best solutions below

0
Garvit Khandelwal On

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