title: Reuse object and its methods in code of multiple @ManagedBeans
body: <p>I want to set my User object only once through my <code>@RequestScoped</code> LoginBean.  Then I want to reuse its setters, getters and an <code>isLoggedIn()</code> method in other @ManagedBean through CDI.</p>
  
  <h2>Request Scoped Class that Sets User Object</h2>
  
  <pre><code>@ManagedBean
  @RequestScoped
  public class LoginBean {
  
      @ManagedProperty(value = "#{bean}")
      protected Bean bean;
  
      private String username;
      private String password;
  
      public String login() {
          bean.setLoggedInUser(userDao.getUser(username));
          return "index";
      }
  
      // Getters and Setters, including for the @ManagedProperty baseBean.
  
  }
  </code></pre>
  
  <h2>SessionScoped Class that Stores User Object</h2>
  
  <pre><code>@ManagedBean
  @SessionScoped
  public class Bean {
  
      private User loggedInUser = null;
  
      public boolean isLoggedIn() {
          return loggedInUser != null;
      }
  
      // Getters and setters for loggedInUser
  
  }
  </code></pre>
  
  <h2>Class Where I Want To Refer to loggedInuser</h2>
  
  <pre><code>@ManagedBean
  @RequestScoped
  public class ShowUserDetails extends Bean {
  
      private Details details = new Details();
  
      public void showDetails() {
      if(isLoggedIn()) { // THIS ALWAYS RETURNS FALSE
            // Do stuff
          }
      }
  
  }
  </code></pre>
  
  <h2>Solutions So Far</h2>
  
  <ul>
  <li>I can list a Bean <code>@ManagedProperty</code> in every single Backing Bean that needs the loggedInUser. This seems wrong as I am copy-pasting two lines in every class.</li>
  <li>I can get the instance of Bean class from FacesContext using <code>context.getApplication().evaluateExpressionGet()</code>.  This allows me to have one method to retrieve Bean instance in a superclass, however this also seems wrong.  That said, this is the method I will go with if I am unable to find a pure CDI solution.</li>
  </ul>