Get Maven basedir from a properties file in a Spri

2019-08-02 08:36发布

问题:

The Maven project I inherited has some resource files used in JUnits.
Those files are referred in a properties file as absolute paths.
Let's assume the Maven project is under myproject, where the main pom.xml resides.

A config.properties file has:

keystore.file=C:/Users/tom/myproject/web/src/test/resources/myfile.jks

I want to refer to that resource from a relative path of the Maven project.
So I have been trying something like:

keystore.file=${project.basedir}/web/src/test/resources/myfile.jks

I have been reading about resource filtering which is referred in this question.

The project uses SpringBoot, and when running a JUnit, complains with:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'project.basedir' in string value "${project.basedir}/web/src/test/resources/myfile.jks"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)

回答1:

After trying different things, found a solution to my problem.
Adding this line in Spring Boot application.properties:

maven.basedir=@project.basedir@

And then in config.properties:

keystore.file=${maven.basedir}/web/src/test/resources/myfile.jks

Makes it work.
Check: Spring Boot automatic Property Expansion Using Maven.