Reputation: 367
I created a bean from class Driver
. When accessing @Autowire
field wait
inside that bean from it's own method everything works fine, but when I call wait
directly inside the bean with driver.wait
I'm getting NullPointerException
. Can someone explain why this is happening?
public class Driver{
@Autowire
public MyWait wait;
public void waitForIt(){
this.wait.doStuff();
}
}
@Component
@Lazy
public class MyWait{
public void doStuff(){
doingStuff();
}
}
@Configuration
@Scope("cucumber-glue")
@ComponentScan(basePackages = {"utilities"})
@Lazy
public class SpringConfig {
@Bean
@Lazy
public Driver getDriver() {
return new Driver();
}
}
@ContextConfiguration(classes = SpringConfig.class)
public Steps{
@Autowire
@Lazy
Driver driver;
public void waitForX(){
driver.waitForIt(); <- works fine
driver.wait.doStuff(); <- java.lang.NullPointerException on wait field
}
Upvotes: 2
Views: 878
Reputation: 44952
Because you are accessing the driver.wait
field using a field reference. Spring auto-wire is based on generated proxies which are applied to methods, especially when some of the beans are @Lazy
. As per docs:
In addition to its role for component initialization, you can also place the
@Lazy
annotation on injection points marked with@Autowired
or@Inject
. In this context, it leads to the injection of a lazy-resolution proxy.
Below should work assuming that there is a corresponding getWait()
method:
driver.getWait().doStuff()
Upvotes: 3