Why call to @Autowired field inside my bean returns null?

Angusiasty :

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
}
Karol Dowbecki :

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()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151179&siteId=1