user2649233
user2649233

Reputation: 912

Passing argument to Autowired constructor in Spring

I have a parameterized constructor. How can I make use of @Autowired annotation within it?

Below is a sample snippet:

@Autowired
private MyImplClass myImplClass;

I have a parameterised constructor in MyImplClass like below:

public class MyImplClass{

    WebDriver driver = new FireFoxDriver();

    public MyImplClass(WebDriver driver){
        this.driver = driver;
    }
}

I need to pass driver to MyImplClass. How this can be achieved using @Autowired?

Upvotes: 5

Views: 8063

Answers (1)

gerrytan
gerrytan

Reputation: 41123

One approach is to create the WebDriver on your spring context:

<bean class="org.openqa.selenium.firefox.FirefoxDriver"/>

And inject it to MyImplClass using constructor autowiring

@Component
public class MyImplClass{

  private WebDriver driver;

  @Autowire
  public MyImplClass(WebDriver driver){
      this.driver = driver;
  }
}

Upvotes: 2

Related Questions