Maven 读取配置文件内容 , 配置文件中读取 Maven pom.xml 中的内容 Maven多环境配置 Maven profiles
一、概述
1、如何从配置文件中读取maven的pom.xml中配置内容呢? 从而实现在maven中的统一管理。
2、实质上,是读取 pom.xml 中的 <properties> 标签,配置的属性值。
3、pom.xml 中,有如下配置:
<properties>
<jdbc.url>jdbc:mysql://localhost:3306/test</jdbc.url>
</properties>
4、标准的maven项目结构中有一个配置文件 jdbc.properties
二、读取配置文件
1、maven pom.xml 中,增加配置:
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
2、jdbc.properties 中,使用 ${} 读取配置:
jdbc.url=${jdbc.url}
3、测试: mvn install ,安装后,查看 jdbc.properties 配置文件是否变成: properties 标签中配置的值, 若还是 ${jdbc.url} ,则说明配置没有成功,失效。
三、多环境配置 Maven profiles
1、如:区分 开发环境和生产环境 ,pom.xml 中添加配置如下:
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<jdbc.url>jdbc:mysql://localhost:3306/test</jdbc.url>
</properties>
<!-- 设置默认环境, install 不带参数,执行这个环境 -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 生产环境 -->
<id>master</id>
<properties>
<jdbc.url>jdbc:mysql://localhost:3306/master</jdbc.url>
</properties>
</profile>
</profiles>
2、启动时,选择对应配置环境: mvn install -P profileId
mvn install -P master
3、在Eclipse中,也可以在 profiles 栏进行配置:
4. 在Idea中使用,配置如下:
四、在Spring Boot项目
1、Spring Boot项目中,读取Maven pom.xml 配置 使用 @xx@
jdbc.url = @jdbc.url@