Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing argument to Autowired constructor in Spring

Tags:

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?

like image 870
user2649233 Avatar asked Nov 02 '22 20:11

user2649233


1 Answers

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;
  }
}
like image 192
gerrytan Avatar answered Nov 15 '22 06:11

gerrytan