spring maven 配置文件 - 根据编译配置文件设置属性文件
我会创建一些这样的编译配置文件:
I would create some compilation profiles like these:
- 个人资料名称:dev
- 个人资料名称:测试
- 个人资料名称:生产
在 src/main/resources 我有 3 个文件夹:
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
在那之后,我会在 Spring 类中设置如下:
After that I would set in Spring classes something like these:
@Configuration
@PropertySource("file:${profile_name}/file.properties")
public class MyConfig{
}
我该怎么办?
参见 Apache Maven 资源插件/过滤 和 Maven:完整参考 - 9.3.资源过滤.(过滤是个坏名字,恕我直言,因为过滤器通常会过滤出的东西,而我们在这里执行字符串插值.但这就是它的方式.)
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.)
在包含 ${...}
的 src/main/resources
中创建 one file.properties
应根据您的环境更改的值的变量.
Create one file.properties
in src/main/resources
that contains ${...}
variables for the values that should change according to your environment.
声明默认属性(那些用于 dev
)并在你的 POM 中激活资源过滤:
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>
...
在 POM 中声明两个具有相应属性的配置文件:
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>
...
在您的代码中仅使用:
@PropertySource("file:file.properties")
使用以下方法激活配置文件:
Activate the profiles with:
mvn ... -P test ...
或
mvn ... -P prod ...