← Back to libraryQuestion 287 of 468
🏗️Framework DesignIntermediate

Page Factory and the @FindBy Pattern

📌 Definition:

Page Factory is a Selenium implementation of POM that uses @FindBy annotations to declare locators and PageFactory.initElements() to initialize them lazily, reducing boilerplate driver.findElement calls.

📖 Detailed Explanation:

Instead of By locators + explicit findElement, you annotate fields: @FindBy(id = "user") private WebElement username; and call PageFactory.initElements(driver, this) in the constructor. Elements are proxied and located lazily WHEN used. Page Factory makes page classes concise, but it has caveats: the lazy proxies can cause StaleElementReferenceException on dynamic pages, and it doesn't integrate as cleanly with explicit waits. Many modern frameworks skip Page Factory in favor of plain By locators + a wait wrapper for more control. Knowing both — and Page Factory's staleness caveat — is a common interview point.

🔑 Key Points:
  • @FindBy declares locators; PageFactory.initElements initializes them
  • Elements located LAZILY when first used (proxied)
  • Concise, but prone to StaleElementReferenceException on dynamic pages
  • Many modern frameworks prefer By + explicit-wait wrappers instead
🌍 Real-World Example:

A page class using @FindBy(css=".submit") WebElement submit; reads cleanly, but on a SPA that re-renders, the proxied element goes stale — pushing the team toward By locators + a waitForClickable helper.

🎯 Scenario-Based Interview Question:

A Page Factory-based test intermittently throws StaleElementReferenceException on a dynamic SPA. Why, and what's a common design fix?