Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one gets loaded first? static block or spring bean?

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?

like image 210
darecoder Avatar asked Oct 03 '17 06:10

darecoder


1 Answers

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

like image 110
TheLostMind Avatar answered Sep 30 '22 16:09

TheLostMind