gpt4 book ai didi

java - 如何分配spring-context?

转载 作者:行者123 更新时间:2023-11-30 10:40:54 25 4
gpt4 key购买 nike

我对 spring 中的应用程序上下文感到非常困惑。如果我使用 spring(简单的 spring)创建一个 beans.xml,然后从(例如)main() 方法调用应用程序上下文。

ApplicationContext context = new FileSystemXmlApplicationContext
("C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml");

一切正常。但我不明白如果我将文件移动到上面的目录或另一个目录(例如),它会好吗?

在 spring-mvc 中,我创建的每个 DispatcherServlet 都有上下文,我在其中指定了一些 bean,所有 servlet 都有公共(public)上下文,如何指定它?在 web.xml 中?总的来说,请在这一刻向我解释(我阅读了 spring in action,我几乎理解了所有内容,但是这些棘手的时刻没有在那里显示。

最佳答案

来自 FileSystemXmlApplicationContext java doc :

Standalone XML application context, taking the context definition files from the file system or from URLs, interpreting plain paths as relative file system locations (e.g. "mydir/myfile.txt"). Useful for test harnesses as well as for standalone environments.

这里的关键词是上下文定义文件,因此您可以根据需要将路径传递给任意数量的 xml 文件。除此之外,您可以创建一个应用程序上下文并将其作为父级传递给新的应用程序上下文:

FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent)

因此,您可以轻松创建所需的上下文层次结构。

       ApplicationContext parentContext = new FileSystemXmlApplicationContext
("C:/some/path/ParentBeans.xml");

ApplicationContext childContext = new FileSystemXmlApplicationContext
(new String[]{"C:/some/path/ChildBeans1.xml", "C:/some/path/ChildBeans2.xml"}, parentContext);

if i move file on directory above all in another directory(for example) it will be ok?

只要您的文件路径正确且可访问 - 就可以。

关于java - 如何分配spring-context?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38720093/

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