Java 直接获取 pom.xml 配置的属性值
系统:Win10
JDK:1.8.0_351
IDEA:2022.3.3
1.需求描述
在开发一个 SpringBoot 项目的时候,需要从 pom.xml 中获取配置的 artifactId,name,version,description 等属性信息,网上查询一番,发现大多数解决方案是通过在 yml 中配置一个自定属性,用 @project.version@ 来获取 pom 中的值,但是这样会多一层配置,比较麻烦,经过一番学习和测试,我发现通过 maven-model 依赖组件可以直接实现在 java 中获取 pom 中的属性值
2.代码示例
pom.xml 配置如下,里面有需要获取的属性值,以及等会需要使用的 maven-model 依赖包
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
</parent>
<groupId>com.lijinjiang</groupId>
<artifactId>SpringBootDemo</artifactId>
<version>1.0.1</version>
<name>SpringBoot测试项目</name>
<description>SpringBootDemo测试项目,用来测试获取pom文件属性值</description>
<properties>
<project.name>DemoName01</project.name>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.7.18</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--配置用于获取pom属性值-->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
</project>
测试代码如下
java
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
MavenXpp3Reader reader = new MavenXpp3Reader();
String myPom = System.getProperty("user.dir") + File.separator + "pom.xml";
try {
Model model = reader.read(new FileReader(myPom));
if (model != null) {
String artifactId = model.getArtifactId();
String version = model.getVersion();
String name = model.getName();
String description = model.getDescription();
System.out.println("artifactId = " + artifactId);
System.out.println("version = " + version);
System.out.println("name = " + name);
System.out.println("description = " + description);
}
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
}
}
3.结果演示
运行上面的测试代码之后,可以在控制台发现需要的属性值已经正确输出了