Search code examples
javaspringsingletonapplicationcontext

What is the usage of refresh() method under AbstractApplicationContext (Spring)? Why is the bean singleton scope lost after using refresh()?


Have used below code to check working of refresh() method under AbstractApplicationContext. But found that due to refresh the beans singleton scope is lost. Confused what exactly happens after singleton is called.

Code used:

public static void main(String[] args) {
        @SuppressWarnings("resource")
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        HelloWorld obj1 = (HelloWorld) context.getBean("helloWorld");
        obj1.setMessage("Object 1...");
        obj1.getMessage();

        context.refresh();
        obj1.getMessage();

        HelloWorld obj2 = (HelloWorld) context.getBean("helloWorld");
        obj2.getMessage();

        context.refresh();

        obj1.getMessage();
        obj2.getMessage();
    }

XML Configuration:

<bean id="helloWorld" class="com.vinaymitbawkar.HelloWorld"
        init-method="init" destroy-method="destroy">
</bean>

Output:

init method
Your Message : Object 1...
destroy method
init method
Your Message : Object 1...
Your Message : null
destroy method
init method
Your Message : Object 1...
Your Message : null

Why does this happen? Why is the singleton scope lost here and obj2 returns null?


Solution

  • The documentation for refresh says:

    Load or refresh the persistent representation of the configuration, which might an XML file, properties file, or relational database schema.

    It's a rather convoluted way of saying that refresh actually loads or re-loads your applicationcontext/bean configurations, from your .xml file or java config. If it helps, think of it as creating a 'new' application context.

    So, your scope does not get 'lost'. Rather you have a re-loaded appcontext which returns you a 'new' singleton bean, which has no message set. Hence you are getting null.