java - 指定属性文件的 Java 路径

标签 java spring file maven-2 properties

我有一个使用 Maven 配置的 Java Spring 项目。随着单元测试及其配置文件的数量迅速增加,我试图将测试配置集中到一个属性文件(同一个,用于构建项目)。

单元测试位于树中(当然,相对于项目路径)

src/test/java/com (...)

The resource files for those tests are in

src/test/resources(...)

And lastly, the properties file, which the resource file should read, is in directory

src/main/filters

Now, I have a Junit class where I specify the configuration file location like this:


@ContextConfiguration(locations = { "classpath:com/initrode/quartz/SyncManagerJobTest-context.xml"})

在配置文件SyncManagerJobTest-context.xml中有一行


<context:property-placeholder location="/src/main/filters/deploy.local.properties"/>

这会导致从目录中读取属性文件。我想阅读的是位于 src/main/filters 下的属性文件。我尝试使用 ../../向上遍历目录,但这没有帮助。使用类路径:也没有成功。我可以使用带有“file:”的绝对路径,但这需要项目中的每个开发人员修改配置,这也不好。

总而言之,问题是:如何强制 src/test/resources/中的配置文件读取 src/main/filters 中的属性文件?

还有一个相关的额外问题:在 Java 环境中处理文件时,除了“file:”和“classpath:”之外还有其他修饰符吗?

最佳答案

如果你指定src/main/filters作为资源位置,Maven会把资源移动到target/classes,同时编译类到相同的位置构建。然后您就没有相对路径来处理,因为它们具有相同的根。如果您不这样做,您的过滤器目录将不会包含在构建中。

更新:当然你的测试代码输出到目标/测试类,所以为了简化测试,你可以指定 src/main/filters 被复制到 target/test -classes 在 process-test-resources 阶段。我修改了示例以显示该行为。

如果您还没有这样做,您可以使用 build-helper-maven-plugin将过滤器文件夹添加为资源位置。

这样做的配置如下所示:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>1.3</version>
  <executions>
    <execution>
      <id>add-resource</id>
      <phase>process-test-sources</phase>
      <goals>
        <goal>add-test-resource</goal>
      </goals>
      <configuration>
        <resources>
          <resource>
            <directory>scr/main/filters</directory>
          </resource>
        </resources>
      </configuration>
    </execution> 
  </executions>
</plugin>

关于java - 指定属性文件的 Java 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1491481/

相关文章:

java - 为了在集合中添加一个对象,是否有必要同时覆盖 equals 和 hashcode。?

java - @Value boolean 返回值 true 的 'invalid boolean value'

java - Spring MVC : How does the "view" work?

php - 复制文本文件的内容并插入到数据库表中,其中给定列等于文本文件的标题

java - BufferedReader指针

java - 在 Mac OS X 扩展坞中锚定 Java 应用程序?

java - 如何使用 JPA 和 Hibernate 在多对多关系中保存具有唯一字段的数据

java - 如何修复我的方法,以便显示以 2 为底的所有幂而不是总和?

spring - Intellij 顶级元素未完成

php - while 循环中的图像