I am autowiring an object of with spring and I am calling a method using the same autowired object. It is throwing NullPointerException. The problem is that I am calling the method inside a static block. Below is my code -
@Autowired
static MyPropertyManagerClass myPropertyManagerClass;
private static URL SERVICE_URL = null;
static {
try {
SERVICE_URL = myPropertyManagerClass.getServiceURL();
}
catch (Exception e) {
log.error("Exception Occurred While Invoking myPropertyManagerClass.getServiceURL() : " , e);
}
}
If I am not wrong, this is happening because static block gets loaded first. Is there any way that I can make this work without creating an object with new keyword?
static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException
(Your dependencies are null) .
Move your code to a method annotated with @PostConstruct
. This will ensure that your code will run when all the dependencies of your component are initialized
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With