title: Design Issue with Automated Test (Selenium WebDriver + Spring Boot + Cucumber + Page Object Model + PageFactory Pattern)
body: <p>I am building an automated test framework using these tools and concepts - </p>
  
  <ul>
  <li>Selenium WebDriver</li>
  <li>Cucumber (For BDD)</li>
  <li>Spring Boot </li>
  <li>Page Object Model</li>
  <li>PageFactory Pattern</li>
  </ul>
  
  <p>Everything is working fine and I am happy with what I have built. Following Page Object Model, I have created PageObject classes which are basically models of actual web pages. I am also using PageFactory pattern to automatically instantiate WebElements.</p>
  
  <p>I have leveraged Spring Boot, for awesomeness. By awesomeness I mean stuff like auto injecting configurations throughout the application, dependency injection required to achieve sharing of the test world between Step Definition classes while performing Cucumber Tests, and other goals which would have been a bit tedious to achieve without it.</p>
  
  <p>Given the background, let's now come to my question.</p>
  
  <p>I want my Page Objects to be Spring managed beans/components. I am initializing my Page Objects using <code>PageFactory.initElements(WebDriver driver, Object page)</code> method from the constructor. As far as my knowledge takes me, if page objects are initialized before the pages are actually loaded in browser, then any attempts to invoke action on their web elements will result in <code>StaleStateException</code>. Correct? So, if I make my page objects Spring managed beans, how do I control the initialization of its web elements? I can remove the PageFactory's initialization method from the constructor and put it in some other method which I can later call to instantiate it. But I wany to know if there is any better approach to this.</p>
  
  <p>The program should be able to autowire page objects in Step Definition classes of Cucumber, but elements of those objects should be instantiated whenever the actual page is loaded in the browser or some action method is called to interact with the web element. </p>
  
  <p><strong>Is it good idea to make PageObjects spring beans, if you are following Page Object Model and PageFactory?</strong> </p>