如何读取到maven中profile设置的参数

一、介绍

maven工程中,我们会用到profiles来配置不同环境的不同的参数。

我们下面介绍如何读取到在这里面设置的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<profiles>
<profile>
<id>local</id>
<properties>
<host>localhost:2333</host>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>dev</id>
<properties>
<host>192.168.10.111:2333</host>
</properties>
</profile>
</profiles>

二、使用

比如说,我们有下面两个文件,example.ymlexample.txt

1
2
example:
host: ${host}
1
请注意,当前host是${host}

在我们使用maven当做我们的包管理构建工具的时候,就可以用到里面的resources标签,来修改我们的文件

只要正确的配置,在构建工程的时候就会修改${}的值,如下进行配置

1
2
3
4
5
6
7
8
9
10
11
12
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/example.yml</include>
<include>**/example.txt</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

接下来就可以进行构建了,如果是在IDEA中的话,可以在此选择对应的profile

image-20240121125232348

自己命令手动构建的话,请加上-PfrofileId,例如mvn clean package -Pdev

构建完成,我们去target目录中看看,发现在编译完成后,相对应的占位位置的值已经发生了变化

image-20240121125841104

三、最后

如何在Java代码中读取?

其实在编译完成后,就可以用@Value读取到值了。具体可以看看我的这篇文章

SpringBoot中读取配置的几种方式 | 半月无霜 (banmoon.top)


如果${}失效的话,请试试@@

1
2
example:
host: @host@

这是因为使用了spring-boot-starter-parent作为父项目,里面有个属性改变了这个占位符

image-20240121130712170

我是半月,你我一同共勉!!!