@FindBy Annotation in Selenium
@FindBy is an annotation from Selenium''s PageFactory class used in the Page Object Model (POM) to identify and initialize web elements.
Basic usage:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
@FindBy(id = "username")
WebElement usernameField;
@FindBy(name = "password")
WebElement passwordField;
@FindBy(xpath = "//button[@type='submit']")
WebElement loginButton;
@FindBy(css = ".error-message")
WebElement errorMessage;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
// @FindBy elements are initialized here
}
public void login(String user, String pass) {
usernameField.sendKeys(user);
passwordField.sendKeys(pass);
loginButton.click();
}
}
Supported locator strategies:
@FindBy(id = "elementId")
@FindBy(name = "elementName")
@FindBy(className = "css-class")
@FindBy(tagName = "input")
@FindBy(linkText = "Click Here")
@FindBy(partialLinkText = "Click")
@FindBy(css = "div.container > input")
@FindBy(xpath = "//div[@class='content']")
Multiple locators with @FindBys (AND logic):
// Finds element with id="search" AND class="active"
@FindBys({
@FindBy(id = "search"),
@FindBy(className = "active")
})
WebElement searchBox;
Multiple locators with @FindAll (OR logic):
// Finds all elements matching EITHER locator
@FindAll({
@FindBy(id = "btn1"),
@FindBy(className = "submit-btn")
})
List<WebElement> buttons;
@FindBy vs driver.findElement():
| Feature | @FindBy (PageFactory) | driver.findElement() |
|---|---|---|
| Code readability | Cleaner, declarative | Verbose, inline |
| Element caching | Lazy (found when used) | Immediate |
| POM integration | Standard approach | Used anywhere |
| StaleElement risk | Higher (cached) | Lower (re-found each time) |
Key point: @FindBy is used to identify elements in the Page Factory approach to POM. Elements are initialized by calling PageFactory.initElements(driver, this) in the page constructor.
