问题
I would create some compilation profiles like these:
- profile name: dev
- profile name: test
- profile name: production
In src/main/resources I have 3 folders:
- dev/file.properties
- test/file.properties
- production/file.properties
Each file contains different values for this properties:
- my.prop.one
- my.prop.two
- my.prop.three
After that I would set in Spring classes something like these:
@Configuration
@PropertySource("file:${profile_name}/file.properties")
public class MyConfig{
}
How can I do?
回答1:
See Apache Maven Resources Plugin / Filtering and Maven: The Complete Reference - 9.3. Resource Filtering. (Filtering is a bad name, IMHO, since a filter usually filters something out, while we perform string interpolation here. But that's how it is.)
Create one file.properties
in src/main/resources
that contains ${...}
variables for the values that should change according to your environment.
Declare default properties (those for dev
) and activate resource filtering in your POM:
<project>
...
<properties>
<!-- dev environment properties,
for test and prod environment properties see <profiles> below -->
<name>dev-value</name>
...
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
...
Declare two profiles with the according properties in your POM:
...
<profiles>
<profile>
<id>test</id>
<properties>
<name>test-value</name>
...
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<name>prod-value</name>
...
</properties>
</profile>
</profiles>
...
Use in your code just:
@PropertySource("file:file.properties")
Activate the profiles with:
mvn ... -P test ...
or
mvn ... -P prod ...
来源:https://stackoverflow.com/questions/48619079/spring-maven-profile-set-properties-file-based-on-compilation-profile