AbstractApplicationContext(Spring)下的refresh()方法有什么用?为什么在使用 refresh() 后 bean 单例作用域丢失了?
What is the usage of refresh() method under AbstractApplicationContext (Spring)? Why is the bean singleton scope lost after using refresh()?
已使用以下代码检查 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 returns 为空?
refresh
的文档说:
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' 应用程序上下文。
因此,您的范围没有得到 'lost'。相反,你有一个重新加载的 appcontext returns 你是一个 'new' 单例 bean,它没有消息集。因此你得到空值。
已使用以下代码检查 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 returns 为空?
refresh
的文档说:
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' 应用程序上下文。
因此,您的范围没有得到 'lost'。相反,你有一个重新加载的 appcontext returns 你是一个 'new' 单例 bean,它没有消息集。因此你得到空值。