selenium-webdriver Using @FindBy annotations in Java Basic example


Assume that we are using Page object model. Page Object class:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LoginPage {
    @FindBy(id="loginInput") //method used to find WebElement, in that case Id
    WebElement loginTextbox;
    WebElement passwordTextBox;
    //xpath example:
    @FindBy(xpath="//form[@id='loginForm']/button(contains(., 'Login')") 
    WebElement loginButton;
    public void login(String username, String password){
        // login method prepared according to Page Object Pattern
        // because WebElements were declared with @FindBy, we can use them without
        // driver.find() method

And Tests class:

class Tests{
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        LoginPage loginPage = new LoginPage();

        //PageFactory is used to find elements with @FindBy specified
        PageFactory.initElements(driver, loginPage);
        loginPage.login("user", "pass");

There are few methods to find WebElements using @FindBy - check Syntax section.