Search code examples
javadependency-injectionscopecdi

Are dependencies with different scopes within an @ApplicationScoped bean reinjected again when the @ApplicationScoped is injected into another class?


I have three classes with different scopes:

// default scope
public class DefaultScopedInstance {
    private String someAttribute;
}

@SessionScoped
public class SomeSessionScopedInstance implements Serializable {
    private String username;
    private String email;
}

@ApplicationScoped
public class UniqueInstance {

    private Clazz someUniqueData; //just an example. could be anything

    @Inject
    private SomeSessionScopedInstance sessionData;

    @Inject
    private DefaultScopedInstance someOtherData;
}

And then inject the UniqueInstance into an JAX-RS Controller (RequestScoped) like this:

@Path("/someService")
public class SomeRestSevice {
    @Inject
    private UniqueInstance uniqueInstance;
}

Are the dependencies of UniqueInstance will be reinjected again for every new request in order to respect their scopes?

This could have a concurrent problem with this design? Like some request accessing the SomeSessionScopedInstance from other users?

Also, this could have a performance issue for some reason?

Thanks!


Solution

  • Are the dependencies of UniqueInstance will be reinjected again for every new request in order to respect their scopes?

    Yes when talking session bean, no for default/dependent. Let's talk @Inject private SomeSessionScopedInstance sessionData; first. This one will always contain the data of the current session of the user has a session, If you try to use it on server side without having one, it will blow up. The details of how this is done are implementation dependent, but for Weld (which you likely use) this is based on thread local variables. It will extract the session which is bound to the thread currently executing your code (this is ofc simplified version of reality).

    As for @Inject private DefaultScopedInstance someOtherData; - this one will not be "reinjected". It is @Dependent meaning it's lifecycle is the same as the object it was injected into which is @ApplicationScoped bean. Therefore it will be same instance as long as that AppScoped bean exists.

    This could have a concurrent problem with this design? Like some request accessing the SomeSessionScopedInstance from other users?

    No, due to what I described above. You only have one session bound to thread and that's that.

    Also, this could have a performance issue for some reason?

    Too vague question. Anything can have perf problems if you code it badly no matter the design behind it.