@ViewScoped bean recreated on every postback request when using JSF 2.2

This,

import javax.faces.view.ViewScoped;

is the JSF 2.2-introduced CDI-specific annotation, intented to be used in combination with CDI-specific bean management annotation @Named.

However, you’re using the JSF-specific bean management annotation @ManagedBean.

import javax.faces.bean.ManagedBean;

You should then be using any of the scopes provided by the very same javax.faces.bean package instead. The right @ViewScoped is over there:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class MenusBean implements Serializable{

If you use the wrong combination, the bean behaves as a @RequestScoped bean and be recreated on each call.

Alternatively, if your environment supports CDI (GlassFish/JBoss/TomEE with Weld, OpenWebBeans, etc), then you could also replace @ManagedBean by @Named:

import javax.inject.Named;
import javax.faces.view.ViewScoped;

@Named
@ViewScoped
public class MenusBean implements Serializable{

It’s recommended to move to CDI. The JSF-specific bean management annotations are candidate for deprecation in future JSF / Java EE versions as everything is slowly moving/unifying towards CDI.

Leave a Comment