Search code examples
jsfdependency-injectioncdijsf-2.2managed-bean

SessionScoped Managed bean injection is not working


This is my SessionScoped managed bean :

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named("clientSessionBean")
@SessionScoped
public class ClientSessionManagedBean implements Serializable {
...
}

This is my requestscoped managed bean

import javax.enterprise.context.RequestScoped; 
import javax.inject.Inject;
import javax.inject.Named;   

@Named("myBean")
@RequestScoped
public class MyManagedBean {

 @Inject
 private ClientSessionManagedBean clientSessionBean;
 ..
 }

The value clientSessionBean giving me null .

How can I inject a sessionScoped bean in a requestscoped managed bean ?

Is there any problem with the package ?


Solution

  • Injected resources are available only after the constructor has run, i.e. during @PostConstruct and beyond. From the spec docs for JSR-250:

    The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization

    As you should be able to infer from the excerpt above, the sequence of events in the lifecycle of a bean is:

    1. Initialization i.e. calling the constructor (the actual mechanism is more complex, but it boils down to this)

    2. Performing injections

    3. Call lifecycle callback, i.e. @PostConstruct. It's at this point, that you're allowed to make use of anything that was created in #2

    Related