Search code examples
jakarta-eecdi

Why does self injection with CDI not result in an infinite loop?


Why this construction works?

@Stateless
public class SomeClass {

    @Inject
    private SomeClass self;

    //...
}

Why is there no infinite recursion of object reference injecting? When does the container realize it's time to stop?


Solution

  • In addition to the Petr's great answer, one of the core concepts of CDI is that you are actually injecting Proxies, not actual objects. When you invoke a function on the proxy, you are routed to the correct bean instance in the container. This allows self-injection to work, as well as other scenarios like Injecting a RequestScoped bean into an ApplicationScoped (how would this work if the container was injecting actual instances?)