Which one is loading first? static block or spring bean?

I run the object using spring and I call the method using the same object that was automatically added. This throws a NullPointerException. The problem is that I am calling a 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'm not mistaken, this is because the static block is loaded first. Is there any way I can do this work without creating an object with a new keyword?

+4
source share
3 answers

static blocks are called when the class is initialized after loading it. The dependencies of your component are not yet initialized. This is why you get NullPointerException(your dependencies are zero).

, @PostConstruct. , .

+2

static spring. @TheLostMind, " @PostConstruct ". new, spring factory-method Xml.

+3

Static will be the first. Spring beans will be initialized after initialization of the BeanPostProcessor level.

+2
source

Source: https://habr.com/ru/post/1686788/


All Articles