5

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?

infojolt
  • 5,244
  • 3
  • 40
  • 82
user2649233
  • 912
  • 4
  • 14
  • 28
  • 1
    You can use the `@Value` annotation. See [this](http://stackoverflow.com/q/6739566/1037210) question. – Lion Jun 11 '13 at 17:38

1 Answers1

2

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;
  }
}
gerrytan
  • 40,313
  • 9
  • 84
  • 99
  • Let me be more clear on this. 'MyImplClass' is in **project1** and 'MyTestClass' is in **project2**. i am using **@Autowired** annotation in 'MyTestClass'. if i had no parameterized constructor in MyImplClass then i would have autowired in the following manner **@Autowired public MyImplClass myImplClass**. But i have a constructor which takes **WebDriver** how do i pass it using @Autowired in **project2** – user2649233 Jun 12 '13 at 06:05
  • without using Autowired annotation, i use to create a object in `MyTestClass in project2` as below. `MyImplClass myImplClass = new MyImplClass(EnumBrowsers.FIREFOX.driver());` How can i achieve the same using Autowired annotation.? – user2649233 Jun 12 '13 at 06:44
  • You never have to pass the constructor argument when you're injecting the object via autowiring. This is because Spring does this for you when the context is initialized. If you don't trust this, print a system out statement on your class constructor. When you boot your program Spring will automatically create an instance of the class with the required constructor arg passed – gerrytan Jun 16 '13 at 03:21