Spring Boot测试中Maven属性扩展是否支持测试资源文件?
Hey there! I’ve faced this exact problem before, so let me break down what’s going on and how to fix it.
The Core Issue
By default, Maven’s resource filtering (which handles those @property@ replacements) does NOT automatically apply to test resource files under src/test/resources. That’s why your application.yml in src/main/resources works fine, but the same setup fails in your test resources.
Why This Happens
Maven’s maven-resources-plugin is configured out of the box to only process files in src/main/resources with filtering enabled. Test resources are treated separately, and filtering is turned off by default for them.
Fixes You Can Try
1. Enable Filtering for All Test Resources
Add this configuration to your pom.xml to turn on filtering for all test resources:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.3.1</version> <executions> <execution> <id>test-resources</id> <phase>process-test-resources</phase> <goals> <goal>testResources</goal> </goals> <configuration> <filtering>true</filtering> </configuration> </execution> </executions> </plugin> </plugins> </build>
2. Filter Only Specific Test Resource Files (Recommended)
If you don’t want to filter every test resource (some files might not need property replacement), you can target specific files like application-test.yml:
<build> <testResources> <testResource> <directory>src/test/resources</directory> <filtering>true</filtering> <includes> <include>application-test.yml</include> </includes> </testResource> <testResource> <directory>src/test/resources</directory> <filtering>false</filtering> <excludes> <exclude>application-test.yml</exclude> </excludes> </testResource> </testResources> </build>
Quick Notes
- Make sure you’re using a recent version of the
maven-resources-pluginto avoid any compatibility quirks. - If you’re using the
spring-boot-maven-plugin, it handles main resource filtering automatically, but test resources still need explicit configuration. - Double-check that the properties you’re trying to replace (like
project.name) are available in your Maven build context—built-in properties like these should work without extra setup.
This is a super common gotcha, so you’re definitely not alone in running into it! Adjusting the resource filtering configuration as above should get your test resources working with Maven property replacements.
内容的提问来源于stack exchange,提问作者Wage

