I use spring and selenium in one project, and I have to wrap WebDriver in such an ugly way:

 @Slf4j @Component public class Firefox { @Getter private WebDriver driver; public Firefox() { driver = new FirefoxDriver(); } } 

And all the time you have to use a getter, which is not very pleasant. How can you achieve that you can write instead

 @Autowired private Firefox firefox; 

And then call firefox.getDriver()

Configure spring so that you can write immediately:

 @Autowired private WebDriver webDriver; 

Taking into account, of course, that in the WebDriver class, the @Component annotation @Component not how not to put it, since it is a library.

Now the config looks like this:

 @Configuration @PropertySource("application.properties") @ComponentScan(basePackages = {"org.example"}) public class SpringBeansConfigurationInjector { @Scope("singleton") @Bean(name = "firefox") Firefox firefox() { return new Firefox(); } } 
  • 2
    What prevents to declare @Bean WebDriver webDriver() { return new FirefoxDriver(); } @Bean WebDriver webDriver() { return new FirefoxDriver(); } in your spring configuration? - Nofate
  • @ Nofate ♦ Isn’t @Component mandatory for @ComponentScan that will search in the specified package? Updated the question. - Pavel
  • one
    @ComponentScan will look for @Component classes. But @Bean simply put WebDriver in a context and make it accessible to @Autowired . - Nofate 5:46 pm
  • one
    The @Scope("singleton") redundant. In spring, everything by default has this scope. - Nofate

1 answer 1

Rewrite the config so:

 @Configuration @PropertySource("application.properties") @ComponentScan(basePackages = {"org.example"}) public class SpringBeansConfigurationInjector { @Bean WebDriver webDriver() { return new FirefoxDriver(); } } 

Now you can implement WebDriver in any other class managed by Spring.

 package org.example; @Component public class SomeClass { @Autowired private WebDriver webDriver; }