Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot reference file location from resources in properties file

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

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.

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.

like image 844
Smajl Avatar asked Dec 23 '22 13:12

Smajl


1 Answers

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

This should hold true whether ...

  • 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
like image 60
glytching Avatar answered Mar 23 '23 00:03

glytching