来自属性文件中资源的Spring Boot参考文件位置 [英] Spring boot reference file location from resources in properties file

查看:83
本文介绍了来自属性文件中资源的Spring Boot参考文件位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring Boot application using Google Pub Sub API. I need to inject Google credentials and other properties using file credentials.json. I put the file in my src/main/resources (otherwise, it will not put the file in the built jar) like this:

spring.cloud.gcp.credentials.location=file:src/main/resources/credentials.json

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

However, when I build the jar, this file is placed in the root directory and this path is no longer valid. So I am able to run my application from Eclipse, since by the that time, the file is still in my resources directory but I can't run it as a standalone jar after built because the path is suddently just file:credentials.json.

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

Is there some easy way how to specify the path as relative so it works both in IDE and when running my jar? I can inject the path through env. variables but I would do so only if absolutely necessary.

推荐答案

如果使用 classpath 前缀,则Spring将在您的classapth上查找文件.

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

如果将文件放在 src/main/resources 中,则Maven默认情况下会将其复制到类路径的根目录,然后可以按以下方式寻址:

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

无论是否...

  • 您正在IDE中运行;您IDE的Maven集成会将文件从 src/main/resources 复制到类路径的根目录-通常是 target/classes
  • 您正在运行内置的JAR;Maven会将文件从 src/main/resources 复制到JAR的根目录
  • You are running in your IDE; your IDE's Maven integration will copy the file from src/main/resources to the root of your classpath - typically target/classes
  • You are running a built JAR; Maven will copy the file from src/main/resources to the root of your JAR

这篇关于来自属性文件中资源的Spring Boot参考文件位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆