AbstractApplicationContext(Spring)下的refresh()方法有什么用?为什么在使用refresh()之后丢失bean单例作用域?

问题描述 投票:0回答:1

已使用以下代码检查AbstractApplicationContext下的refresh()方法的工作情况。但是发现由于刷新而使bean的单例作用域丢失了。令人困惑的是在调用单例之后究竟发生了什么。

使用的代码:

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配置:

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

输出:

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

为什么会这样?为什么单例作用域在这里丢失,而obj2返回null?

java spring singleton applicationcontext
1个回答
0
投票

refresh的文档说:

加载或刷新配置的持久表示,可能是XML文件,属性文件或关系数据库模式。

这是一种相当复杂的说法,刷新实际上是从.xml文件或Java配置加载或重新加载applicationcontext / bean配置。如果有帮助,可以将其视为创建“新”应用程序上下文。

因此,您的范围不会丢失。相反,您有一个重新加载的appcontext,它会向您返回一个没有消息集的“新”单例bean。因此,您将得到null。

© www.soinside.com 2019 - 2024. All rights reserved.