I have a class that I call from another class:
public class caller {
@Test
public void test() throws Exception {
Calle.getInstance().run();
}
}
---------------------------------------------------------------------------
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Swagger2SpringBoot.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("api")
public final class Calle extends AbstractTest {
@Autowired
private UserApi userApi;
private static final Calle INSTANCE = new Calle();
public static Calle getInstance() {
return Calle.INSTANCE;
}
private Calle() {
}
public void run() throws Exception {
final User usr1 = this.createUser(this.userApi);
}
}
MAIN
@ComponentScan(
basePackages = {
"es.comp.api",
"es.comp.api.controller",
"es.comp.api.configuration"
}
The UserApi class is added in the main ("es.comp.api.controller",)
Apparently and from what I could read. When a class is called in a singleton. Spring does not load dependencies that are loaded with the @Autowired tag. So when doing the this.createUser(this.userApi) it gives me a NullPointerException.
How could I solve this error? All the best
When you use Spring to instantiate any object, Spring takes care of parsing its class and finding dependencies. If you create an instance of any class by manually calling its constructor, that instance is not known to Spring and therefore it won't inject anything into it. The easiest solution would be to keep using Spring to get the instance, something like: