ViewScoped Bean cause NotSerializableException

前端 未结 3 2104
半阙折子戏
半阙折子戏 2020-12-06 18:06

Hello I\'m using a ViewScoped Bean the Problem is that when call it I get the NotSerializableException.

This is the code of my Managed Bean :

@Manage         


        
3条回答
  •  一个人的身影
    2020-12-06 18:14

    I posted a solution for this problem on my own question about this same problem, that goes like this: instead of injecting the Spring beans via EL in a @ManagedProperty annotation (executed on the ManagedBean initialization), you obtain the beans evaluating the EL at runtime.

    With this approach, your JSF bean should look like this:

    @ManagedBean(name="demandesBean")
    @ViewScoped
    public class DemandesBean implements Serializable {
        private static final long serialVersionUID = 1L;
    
        private static DemandeService demandeService() {
            return SpringJSFUtil.getBean("demandeService");
        }
    
        // ... 
        public void doAjouterDemande(ActionListener event) {
            demandeService().createDemande(newDemande, loginBean.getUsername());
            newDemande = new DemandeVO();
        }
        // ...
    

    And here it is the used utility class SpringJSFUtil.java:

    import javax.faces.context.FacesContext;
    
    public class SpringJSFUtil {
    
        public static  T getBean(String beanName) {
            if (beanName == null) {
                return null;
            }
            return getValue("#{" + beanName + "}");
        }
    
        @SuppressWarnings("unchecked")
        private static  T getValue(String expression) {
            FacesContext context = FacesContext.getCurrentInstance();
            return (T) context.getApplication().evaluateExpressionGet(context,
                    expression, Object.class);
        }
    }
    

    This eliminates the Spring bean property (at the cost of doing a few more EL evaluations), thus avoiding the serialization issues of having the property in first place.

提交回复
热议问题