【发布时间】:2014-01-19 18:55:16
【问题描述】:
我已经阅读了动态 bean 定义更改。我在一个简单的代码示例中尝试了它(参见下面的代码),我发现它在我不想停止服务器但添加/更改 bean 定义的情况下非常有吸引力。
问题:
- 这样做安全吗(见下面的代码)?
-
我读到有可能在
StaticApplicationContex或BeanPostProcessor或BeanFactoryPostProcessor的帮助下在运行时实现 bean 定义更改?那么有什么区别呢?public class Main { final static String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<beans xmlns=\"http://www.springframework.org/schema/beans\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xmlns:context=\"http://www.springframework.org/schema/context\"\n" + " xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n" + " <context:annotation-config />\n" + " <context:component-scan base-package=\"vbah\"/>"; final static String contextA = "<bean id=\"test\" class=\"java.lang.String\">\n" + "\t\t<constructor-arg value=\"fromContextA\"/>\n" + "</bean></beans>"; final static String contextB = "<bean id=\"test\" class=\"java.lang.String\">\n" + "\t\t<constructor-arg value=\"fromContextB\"/>\n" + "</bean></beans>"; public static void main(String[] args) throws IOException { //create a single context file final File contextFile = new File("src/resources/spring-config.xml"); //write the first context into it FileUtils.writeStringToFile(contextFile, header + contextA); //create a spring context FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( new String[]{contextFile.getPath()} ); //echo "fromContextA" System.out.println(context.getBean("test")); //write the second context into it FileUtils.writeStringToFile(contextFile, header + contextB); //refresh the context context.refresh(); //echo "fromContextB" System.out.println(context.getBean("test")); } }
编辑:
你能回答以下问题吗:
- 据我了解,
BeanPostProcess允许您在运行时通过使用代理包装对象来修改已存在的 bean 实例。我说的对吗? -
AbstractApplicationContext#refresh() 删除所有单例 bean 并重新创建它们。
- 但是如果我想更改原型/自定义范围 bean 的定义?
- 如果我有两个 bean:A 和 B。A 引用 B。如果我以不包含 B 定义的方式更改 bean 定义。B 实例将被销毁,但新实例不会被创建。比 A 会得到一个
null依赖。我说的对吗?
StaticApplicationContext和BeanFactoryPostProcessor都允许我在运行时更改 bean 定义。但是有什么区别,优点/缺点?-
[主要问题] 为什么 Spring 有 3 种机制来实现相同的目标。请在
AbstractApplicationContext#refresh()、StaticApplicationContext和BeanFactoryPostProcessor之间做一个简短的比较(或用例示例)。
【问题讨论】: