gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:29:22 26 4
gpt4 key购买 nike

使用下面的代码来检查 AbstractApplicationContext 下的刷新()方法的工作情况。但发现由于刷新beans单例范围丢失了。混淆调用单例后到底发生了什么。

使用的代码:

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?

最佳答案

刷新的文档说:

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

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

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

关于java - AbstractApplicationContext(Spring)下的refresh()方法有什么用?为什么使用refresh()后bean单例作用域会丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61153237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com