I have a parent class and a child class shown below:
@Component
public class Parent {
public AndroidDriver<MobileElement> driver;
public void method() {};
}
@Component
public class Child extends Parent {
@Override
public void method() {
//do something with the parent's driver variable
driver.findElement(...);
}
}
Now in my main class, I injected these two classes. For the record I have to set the driver variable like below after I got some inputs from the user.
@Resource
private Parent parent;
@Resource
private Child child;
private static ConfigurableApplicationContext applicationContext;
public static void main(String[] args)
{
applicationContext = SpringApplication.run(DemoAppiumProjectApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx)
{
//Get some value from the user input, then set driver;
parent.setDriver(new AndroidDriver<>(${some input from the user}));
child.method();
}
My guess is that the parent.setDriver(driver) is set but it's not the parent instance of the injected child class that it extends, so when it goes down to child.method, the driver variable is null and end up with NullPointerException.
I can call child.setDriver to achieve my goal, but what if I have a set of children and I only want the setDriver to be called once by the parent, then all children class can access it. How can I do this correctly?