在普通的Maven项目和Maven插件项目中,我如何访问在pom文件中定义的Maven属性?
在普通的Maven项目和Maven插件项目中,我如何访问在pom文件中定义的Maven属性?
properties
写入文件,然后在运行时读取该文件。在您的pom.xml中实现:<properties>
<name>${project.name}</name>
<version>${project.version}</version>
<foo>bar</foo>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
然后在 .java 文件中:
java.io.InputStream is = this.getClass().getResourceAsStream("my.properties");
java.util.Properties p = new Properties();
p.load(is);
String name = p.getProperty("name");
String version = p.getProperty("version");
String foo = p.getProperty("foo");
compile
。不确定这是否是正确的解决方案。 - Nikita Bosikmaven-resource-plugin
相结合来实现。Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
try {
reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
model = mavenreader.read(reader);
model.setPomFile(pomfile);
}catch(Exception ex){
// do something better here
ex.printStackTrace()
}
MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need
使用以下内容很重要:
this.getClass().getClassLoader().getResourceAsStream("maven.properties");
而不仅仅是
this.getClass().getResourceAsStream("maven.properties");
maven.properties
文件正确地写到project.build.outputDirectory
中:<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}/maven.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
这里的解释是正确的。
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
...
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
<configuration>
...
</configuration>
</plugin>
在我的代码中:
@Autowired
BuildProperties buildProperties;
...
@GetMapping
public Map<String, String> getVersion() {
return Map.of(
"build.name", buildProperties.getName(),
"build.version", buildProperties.getVersion(),
"build.date", buildProperties.getTime().toString());
}
关于此插件目标的更多信息可以在此处找到:https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/#goals-build-info