类加载器如何找到资源?

How does the classloader find resources?

我正在审查一个小型 github 示例项目 (shagie/TestingWithHsqldb),并且偶然发现了一个对我来说很陌生的约定,希望有人能帮助我理解我正在查看的内容。


项目是这样组织在主 src 目录下的...

src/main/resources/connection_config.properties
src/main/java/com/shagie/dbtest/db/DBConnection.java
src/main/java/com/shagie/dbtest/db/DataAccess.java

src/test/resources/connection_config.properties
src/test/java/com/shagie/dbtest/db/DataAccessTest.java

DBConnection.java 中的代码被 'main' 目录下的 DataAccess.java 和 'test' 目录下的 DataAccessTest.java 调用。

在文件 DBConnection.java 中有以下导入 connection_config.properties 文件的语句:

Properties prop = new Properties();
InputStream in = GetClass().getResourceAsStream("/connection_config.properties");
prop.load(in);
in.close();

我的问题...

编辑:调整问题以关注ClassLoadergetResource功能而不是依赖注入

这与依赖注入无关,但与 ClassLoader 解析资源路径的方式有关。

1) 来自 Linux 背景的这可能有点令人困惑,实际上 getResourceAsStream(resource) 有不同的规则。根据 doc:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

所以这里的前导斜杠只是告诉class加载器如何获取绝对名称(你传递的名称是否应该以包名开头),而不是它应该寻找"at the root"(在 test/main 文件夹中)。什么是根以及解析的工作原理取决于您使用的 class 加载程序。默认情况下(在这种情况下)在 resources 文件夹中搜索资源。您可以编写自己的 ClassLoader 并更改该行为。

2) 同样,当调用 getResources()getResourceAsStream() 时,class 将其委托给加载此 class 的 ClassLoader。如果你是 运行 单元测试(Junit 或类似的东西)那么 ClassLoader 会知道它应该在 test 文件夹而不是 main.[=22= 中寻找资源]