java - 用于 Spring ApplicationContext 创建的前缀到底如何工作?

标签 java spring spring-mvc applicationcontext

我正在学习 Spring Core 认证,对于如何在 Spring 4 应用程序中正确声明新的 FileSystemXmlApplicationContext 存在疑问。

我知道,在我的 ma​​in() 方法中,我可以有这样的东西:

ApplicationContext context = new FileSystemXmlApplicationContext("classpath:mycompany.mydivision.myapplication.application.config.xml", "file:test-infra-config.xml");

所以,如果我说的是错误的断言,请纠正我,这一行从两个不同的文件创建 Spring 应用程序上下文(我从中获取 bean 的对象),其中包含我的应用程序的 bean 定义,分别名为 config.xmltest-infra-config.xml

我的疑问是:第一个来自类路径,第二个来自文件,这到底意味着什么?

我认为第二个路径相对于JVM工作目录,第一个路径来自应用程序类路径(在项目中定义,或者是什么?)

我的疑问是:在Spring 4中是否必须使用classpath:file:前缀?

据我所知,我可以省略 file: 前缀,但不能省略 classpath: 前缀(但我不确定 Spring 3 版本中是否如此)或者如果它正在更改 4 版本中的某些内容)。如果这是真的,为什么我可以省略 file: 前缀而不是 classpath: 前缀?

Tnx

最佳答案

很多问题:

I think that the second one path is relative to the the JVM working directory and

正确


the first one from the application classpath (definied in the project, or what?)

它是 JVM 在运行应用程序时使用的类路径


My doubts are: in Spring 4 are the use of the classpath: and of the file: prefix mandatory?

JavaDoc of FileSystemXmlApplicationContext开始于

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.

NOTE: Plain paths will always be interpreted as relative to the current VM working directory, even if they start with a slash. (This is consistent with the semantics in a Servlet container.) Use an explicit "file:" prefix to enforce an absolute file path.


From what I have understand I can omit the file: prefix but not the classpath: prefix (but I am not sure if it is true in the Spring 3 version or if it is changing something in the 4 version).

正确(Spring 3 和 4 之间没有变化(参见 javadoc))


If it is true why I can omit the file: prefix but not the classpath: prefix?

因为你只能有一个默认值:当你没有指定路径是引用文件(系统)还是类路径时,spring 必须决定在哪里搜索文件 - 他们决定将其作为一个文件(系统)引用

(我也可以想象这可能是因为一些历史和向后兼容,也许 Spring 的第一个版本此时只支持没有任何前缀的文件方式。 - 但这是一个猜测,没有知识)

关于java - 用于 Spring ApplicationContext 创建的前缀到底如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29601076/

相关文章:

java - 为什么 new File(File Parent, String childName) 表现不明显?

java - Page<T> 对象在 foreach 循环中抛出 NPE

java - 如何保护@ConfigurationProperties 类免受更改?

Java/抽象类

java - 在 ResponseEntity 主体中返回 null(Spring Boot RESTful)

java - Spring事务和 hibernate : lazy initialization

java - 给定 View 类 [org.springframework.web.servlet.view.tiles3.TilesView] 不是 [org.springframework.web.servlet.view.AbstractUrlBasedView] 类型

java - Spring Security 可以在 Spring Controller 方法上使用 @PreAuthorize 吗?

java - Spring MVC 可重用 View 组件

java.lang.NoClassDefFoundError : org/springframework/security/converter/RsaKeyConverters 错误