0

I know there are loads of questions on SO regarding this exact issue, but I couldn't find a solution to my problem. I'm trying to use a @ManagedProperty in JSF 2. I used the example from this page, but mine's not working:

@ManagedProperty("#{userSession}")
private UserSession userSession;
public void setUserSession(UserSession userSession) {
    this.userSession = userSession;
}

Both the parent bean and the bean injected are session scoped. Both beans have the @ManagedBean attribute. No faces-config.xml declarations, no EJBs, no use of Spring. One thing I noticed from that example is that both the bean classes implement Serializable. Mine do not, and I'm not sure if that is making the difference.

When I use this code, I get a NullPointerException when I try to operate on userSession. However, I know a session exists, because when I use @BalusC's findBean convenience method, it works. One thing with this though, is that my code only works if I call userSession = findBean("userSession") inside the same method where I'm "doing stuff". If I initialize userSession in the bean's constructor, I get another NPE. Any ideas?

Community
  • 1
  • 1
neizan
  • 2,291
  • 2
  • 37
  • 52
  • Where exactly are you trying to access it? In the constructor? – BalusC Aug 22 '13 at 21:10
  • No getter for that bean. Also, is it throwing the NPE for the actual bean or a chained call to a member of the bean? – kolossus Aug 23 '13 at 04:22
  • @BalusC I'm trying to access it in a private method, which is called in the constructor. – neizan Aug 23 '13 at 06:40
  • @kolossus A getter for which bean? You mean the ManagedProperty? Do I need a getter for the ManagedProperty if I only intend to access it from within the bean class? It is throwing a NPE when I try to do, e.g., `userSession.isAuthenticated()`. Also, after switching to using the `findBean` convenience method to init `userSession` immediately before use (and changing nothing else), the code worked as anticipated. So, doing it the `ManagedProperty` way (or the `findBean` way from inside the constructor is givng me `userSession == null`. – neizan Aug 23 '13 at 06:50
  • I've sometimes found when adding a new bean that I needed to restart the container for it to apply correctly. Doing a hot-redeploy of an application isn't always enough. – mrswadge Nov 17 '16 at 14:11

0 Answers0