NullPointerException while trying to access @Inject bean in constructor

后端 未结 2 2069
别跟我提以往
别跟我提以往 2020-11-29 06:59

I\'ve a session scoped bean:

@Named
@SessionScoped
public class SessionBean implements Serializable {

    private String someProperty;

    public String ge         


        
相关标签:
2条回答
  • 2020-11-29 07:36

    You're expecting that the injected dependency is available before the bean is constructed. You're expecting that it works like this:

    RequestBean requestBean;
    requestBean.sessionBean = sessionBean; // Injection.
    requestBean = new RequestBean(); // Constructor invoked.
    

    This is however not true and technically impossible. The dependencies are injected after construction.

    RequestBean requestBean;
    requestBean = new RequestBean(); // Constructor invoked.
    requestBean.sessionBean = sessionBean; // Injection.
    

    You should be using a @PostConstruct method instead if you intend to perform business logic based on injected dependencies directly after bean's construction.

    Remove the constructor and add this method:

    @PostConstruct
    public void init() {
        System.out.println(sessionBean.getSomeProperty());
    }
    
    0 讨论(0)
  • 2020-11-29 07:37

    BalusC's reply is correct, but is does reflect the assignment phase of a object creation, that did not run at this time. But anyway the CDI bean should be accessible if you grep it programatically via:

    javax.enterprise.inject.spi.CDI.current().select(SessionBean.class).get()
    
    0 讨论(0)
提交回复
热议问题