@ManagedProperty does not reflect changes and keeps returning null

后端 未结 5 1974
花落未央
花落未央 2021-01-14 11:07

I\'m trying to inject the value of one sessionscoped bean into a viewscoped bean but it keeps returning null, here\'s a snippet:

import javax.faces.applicati         


        
5条回答
  •  北海茫月
    2021-01-14 11:29

    I had this problem, and the problem was actually twofold. (Note also that @ManagedProperty will only ever work in a @ManagedBean class and if that @ManagedProperty class is of the same or lesser scope (application, session, view, request, etc.).) Here is how I fixed it:


    Problem 1: JSF is stupid and doesn't handle @ManagedProperty injection properly in abstract classes.

    Solution:

    1. Make every class that uses @ManagedProperty be annotated with @ManagedBean.
    2. Make every abstract class that uses the property not be annotated with @ManagedProperty and instead only provide abstract getter and setter methods that non-abstract classes will each override.
    3. Use the abstract class's getter method instead of the @ManagedProperty itself in abstract classes.

    Problem 2: JSF is stupid and doesn't handle @ManagedProperty injection properly in @ManagedBean classes not created by JSF (i.e. you are creating these classes yourself using new).

    Solution options:

    • Let JSF create the class that uses the @ManagedProperty.
    • Use the following code:

    MyClass example = Utils.getELValue("EL Expression Goes Here", MyClass.class);
    
    public static  T getELValue(final String elName, final Class clazz) {
      FacesContext fc = FacesContext.getCurrentInstance();
      return (T) fc.getApplication().getELResolver().getValue(fc.getELContext(), null, elName);
    
      // Potential (untested) alternative:
      // ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getSession().getAttribute("")
    }
    

提交回复
热议问题