title: JSF View Scoped Bean Reconstructed Multiple Times
body: <p>I thought <code>@ViewScoped</code> was supposed to prevent the bean from being reconstructed while the user is on the same page... So why is my <code>@ViewScoped</code> JSf controller bean being created multiple times even before the action handler causes the browser to navigate away from that view?</p>
  
  <p>Can anyone point me in the right direction here?</p>
  
  <p>Here is my code:</p>
  
  <h2>The View (domain/edit.xhtml)</h2>
  
  <pre><code>&lt;h:form prependId="false"&gt;
      &lt;h:inputText id="descriptionField" value="#{domainEdit.domain.description}" /&gt;
      &lt;h:commandButton id="saveButton" value="save" action="#{domainEdit.save}" /&gt;
  &lt;/h:form&gt;
  </code></pre>
  
  <h2>The ViewScoped controller (DomainEdit.java)</h2>
  
  <pre><code>@Named("domainEdit")
  @ViewScoped
  public class DomainEdit implements Serializable {
  
      private static final long serialVersionUID = 1L;
  
  
      protected DomainEdit() {
      }
  
      @PostConstruct
      protected void init() {
          System.out.println("post construct called.");
      }
  
      @PreDestroy
      public void destroy() {
          System.out.println("pre destroy called.");
      }
  
      public DomainEntity getDomain() {
          System.out.println("displaying domain...");
  
          // some code to return the domain
          return domain;
      }
  
      public String save() {
          System.out.println("saving...");
  
          // some saving code
  
          return "view";
      }
  }
  </code></pre>
  
  <h2>Output</h2>
  
  <p>I get the following output when I deploy this and perform the following:</p>
  
  <ol>
  <li><p>Navigate to the edit view (edit.xhtml)</p>
  
  <blockquote>
  <pre><code>   post construct called.
     displaying domain...
     pre destroy called.
  </code></pre>
  </blockquote></li>
  <li><p>Change the content of the domainDescriptionField input text</p>
  
  <p><em>nothing logged</em></p></li>
  <li><p>Click 'save'</p></li>
  </ol>
  
  <blockquote>
  <pre><code>  post construct called.
    displaying domain...
    pre destroy called.
  
    post construct called.
    displaying domain...
    pre destroy called.
  
    post construct called.
    displaying domain...
    pre destroy called.
  
    post construct called.
    displaying domain...
    pre destroy called.
  
    post construct called.
    displaying domain...
    saving domain...
    pre destroy called.
  </code></pre>
  </blockquote>