Java 在运行时获取Maven工件版本
我注意到在Maven工件的JAR中,project.version属性包含在两个文件中:Java 在运行时获取Maven工件版本,java,maven-2,Java,Maven 2,我注意到在Maven工件的JAR中,project.version属性包含在两个文件中: META-INF/maven/${groupId}/${artifactId}/pom.properties META-INF/maven/${groupId}/${artifactId}/pom.xml 有没有建议在运行时读取此版本的方法?您不需要访问特定于Maven的文件来获取任何给定库/类的版本信息 您只需使用getClass().getPackage().getImplementationVers
META-INF/maven/${groupId}/${artifactId}/pom.properties
META-INF/maven/${groupId}/${artifactId}/pom.xml
有没有建议在运行时读取此版本的方法?您不需要访问特定于Maven的文件来获取任何给定库/类的版本信息 您只需使用
getClass().getPackage().getImplementationVersion()
即可获取存储在.jar文件MANIFEST.MF
中的版本信息。幸运的是Maven足够聪明,不幸的是Maven在默认情况下也没有将正确的信息写入清单
相反,我们必须修改
来跟进上面的答案,对于.war
工件,我发现我必须将等效配置应用于maven-war-plugin
,而不是maven-jar-plugin
:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
maven战争插件
2.1
真的
真的
这将把版本信息添加到项目的.jar
中的MANIFEST.MF
(包含在.war
的WEB-INF/lib
中)以下是一种从pom.properties获取版本的方法,可以从MANIFEST获取版本
public synchronized String getVersion() {
String version = null;
// try to load from maven properties first
try {
Properties p = new Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
}
// fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
我花了一些时间在这两种主要的方法上,但它们并不适合我。我正在使用Netbeans进行构建,可能还有更多的工作要做。我在Maven 3的一些构造中遇到了一些错误和警告,但我认为这些很容易纠正。没什么大不了的
在这篇关于DZone的文章中,我确实找到了一个看起来可维护且易于实现的答案:
我已经有了一个resources/config子文件夹,我将我的文件命名为app.properties,以更好地反映我们可能保存在那里的内容(如支持URL等)
唯一需要注意的是,Netbeans会发出警告,提示IDE需要过滤掉。不知道在哪里/如何。在这一点上没有效果。如果我需要穿过那座桥,也许有一个解决办法。祝您好运。要在Eclipse和Maven版本中运行此功能,您应该添加addDefaultImplementationEntries
和addDefaultSpecificationEntries
pom条目,如其他回复中所述,然后使用以下代码:
public synchronized static final String getVersion() {
// Try to get version number from pom.xml (available in Eclipse)
try {
String className = getClass().getName();
String classfileName = "/" + className.replace('.', '/') + ".class";
URL classfileResource = getClass().getResource(classfileName);
if (classfileResource != null) {
Path absolutePackagePath = Paths.get(classfileResource.toURI())
.getParent();
int packagePathSegments = className.length()
- className.replace(".", "").length();
// Remove package segments from path, plus two more levels
// for "target/classes", which is the standard location for
// classes in Eclipse.
Path path = absolutePackagePath;
for (int i = 0, segmentsToRemove = packagePathSegments + 2;
i < segmentsToRemove; i++) {
path = path.getParent();
}
Path pom = path.resolve("pom.xml");
try (InputStream is = Files.newInputStream(pom)) {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(is);
doc.getDocumentElement().normalize();
String version = (String) XPathFactory.newInstance()
.newXPath().compile("/project/version")
.evaluate(doc, XPathConstants.STRING);
if (version != null) {
version = version.trim();
if (!version.isEmpty()) {
return version;
}
}
}
}
} catch (Exception e) {
// Ignore
}
// Try to get version number from maven properties in jar's META-INF
try (InputStream is = getClass()
.getResourceAsStream("/META-INF/maven/" + MAVEN_PACKAGE + "/"
+ MAVEN_ARTIFACT + "/pom.properties")) {
if (is != null) {
Properties p = new Properties();
p.load(is);
String version = p.getProperty("version", "").trim();
if (!version.isEmpty()) {
return version;
}
}
} catch (Exception e) {
// Ignore
}
// Fallback to using Java API to get version from MANIFEST.MF
String version = null;
Package pkg = getClass().getPackage();
if (pkg != null) {
version = pkg.getImplementationVersion();
if (version == null) {
version = pkg.getSpecificationVersion();
}
}
version = version == null ? "" : version.trim();
return version.isEmpty() ? "unknown" : version;
}
公共同步静态最终字符串getVersion(){
//尝试从pom.xml(在Eclipse中提供)获取版本号
试一试{
字符串className=getClass().getName();
字符串classfileName=“/”+className.replace(“.”,“/”)+“.class”;
URL classfileResource=getClass().getResource(classfileName);
if(classfileResource!=null){
Path absolutePackagePath=Path.get(classfileResource.toURI())
.getParent();
int-packagePathSegments=className.length()
-className.replace(“.”,“”)。length();
//从路径中删除包段,再加上两个级别
//对于“目标/类别”,这是
//Eclipse中的类。
路径路径=绝对打包路径;
对于(int i=0,segmentsToRemove=packagePathSegments+2;
i
如果您的Java构建将目标类放置在“target/classes”之外的某个位置,那么您可能需要调整segmentsToRemove的值。我正在使用maven assembly plugin
进行maven打包。in的使用也可以起到以下作用:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
<executions>
<execution .../>
</executions>
</plugin>
org.apache.maven.plugins
,它可以被多个maven构建插件使用,如果引入两个或多个插件,其中包括archive
configuration in。在EAP 7.0上测试
@Log4j // lombok annotation
@Startup
@Singleton
public class ApplicationLogic {
public static final String DEVELOPMENT_APPLICATION_NAME = "application";
public static final String DEVELOPMENT_GROUP_NAME = "com.group";
private static final String POM_PROPERTIES_LOCATION = "/META-INF/maven/" + DEVELOPMENT_GROUP_NAME + "/" + DEVELOPMENT_APPLICATION_NAME + "/pom.properties";
// In case no pom.properties file was generated or wrong location is configured, no pom.properties loading is done; otherwise VERSION will be assigned later
public static String VERSION = "No pom.properties file present in folder " + POM_PROPERTIES_LOCATION;
private static final String VERSION_ERROR = "Version could not be determinated";
{
Optional.ofNullable(getClass().getResourceAsStream(POM_PROPERTIES_LOCATION)).ifPresent(p -> {
Properties properties = new Properties();
try {
properties.load(p);
VERSION = properties.getProperty("version", VERSION_ERROR);
} catch (Exception e) {
VERSION = VERSION_ERROR;
log.fatal("Unexpected error occured during loading process of pom.properties file in META-INF folder!");
}
});
}
}
在我的spring boot应用程序中,来自公认答案的解决方案一直有效,直到我最近将jdk更新为版本12。也尝试了所有其他答案,但都无法实现
此时,我在我的spring boot应用程序的第一个类中添加了下面的一行,就在注释
@Log4j // lombok annotation
@Startup
@Singleton
public class ApplicationLogic {
public static final String DEVELOPMENT_APPLICATION_NAME = "application";
public static final String DEVELOPMENT_GROUP_NAME = "com.group";
private static final String POM_PROPERTIES_LOCATION = "/META-INF/maven/" + DEVELOPMENT_GROUP_NAME + "/" + DEVELOPMENT_APPLICATION_NAME + "/pom.properties";
// In case no pom.properties file was generated or wrong location is configured, no pom.properties loading is done; otherwise VERSION will be assigned later
public static String VERSION = "No pom.properties file present in folder " + POM_PROPERTIES_LOCATION;
private static final String VERSION_ERROR = "Version could not be determinated";
{
Optional.ofNullable(getClass().getResourceAsStream(POM_PROPERTIES_LOCATION)).ifPresent(p -> {
Properties properties = new Properties();
try {
properties.load(p);
VERSION = properties.getProperty("version", VERSION_ERROR);
} catch (Exception e) {
VERSION = VERSION_ERROR;
log.fatal("Unexpected error occured during loading process of pom.properties file in META-INF folder!");
}
});
}
}
@PropertySources({
@PropertySource("/META-INF/maven/com.my.group/my-artefact/pom.properties")
})
@Value("${version}")
private String appVersion;
private static Optional<String> getVersionFromManifest(Class<?> clazz) {
try {
File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
if (file.isFile()) {
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
Attributes attributes = manifest.getMainAttributes();
final String version = attributes.getValue("Bundle-Version");
return Optional.of(version);
}
} catch (Exception e) {
// ignore
}
return Optional.empty();
}
@Configuration
@RequiredArgsConstructor // <- lombok
public class OpenApi {
private final BuildProperties buildProperties; // <- you can also autowire it
@Bean
public OpenAPI yourBeautifulAPI() {
return new OpenAPI().info(new Info()
.title(buildProperties.getName())
.description("The description")
.version(buildProperties.getVersion())
.license(new License().name("Your company")));
}
}
<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>
</plugin>
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class CommonControllerAdvice
{
@Autowired
BuildProperties buildProperties;
@ModelAttribute("version")
public String getVersion() throws IOException
{
String version = buildProperties.getVersion();
return version;
}
}