来自属性文件中资源的Spring Boot参考文件位置

Sma*_*ajl 1 java spring-boot

我有一个使用Google Pub Sub API的Spring Boot应用程序。我需要使用file注入Google凭据和其他属性credentials.json。我将文件放入我的文件中src/main/resources(否则,它将不会将文件放入构建的jar中),如下所示:

spring.cloud.gcp.credentials.location=file:src/main/resources/credentials.json
Run Code Online (Sandbox Code Playgroud)

但是,当我构建jar时,此文件将放置在根目录中,并且该路径不再有效。因此,我能够从Eclipse运行我的应用程序,因为到那时,该文件仍位于我的资源目录中,但是构建后我无法将其作为独立的jar运行,因为该路径突然只是file:credentials.json

有什么简单的方法可以将路径指定为相对路径,以便它既可以在IDE中运行,又可以在运行jar时使用?我可以通过env注入路径。变量,但只有在绝对必要时,我才会这样做。

gly*_*ing 5

If you use the classpath prefix then Spring will look for the file on your classapth.

If you put the file in src/main/resources then Maven will, by default, copy it to the root of your classpath and it will then be addressable as follows:

spring.cloud.gcp.credentials.location=classpath:credentials.json
Run Code Online (Sandbox Code Playgroud)

This should hold true whether ...

  • 您正在IDE中运行;您的IDE的Maven集成会将文件从复制src/main/resources到您的类路径的根目录-通常target/classes
  • 您正在运行一个内置的JAR;Maven会将文件从复制src/main/resources到JAR的根目录