pom.xml中配置,生产上可以将maven-model.jar删除
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.0</version>
</dependency>
java代码如下
package com.loveU;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Properties;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
/**
* <pre>
* <b>类描述:</b> maven版本号获取
* <b>创建日期:</b>2018年5月16日 下午9:29:02
* </pre>
*/
public class VersionUtil {
public static String appVersion = null;
/**
* @return 获取版本号
*
* @throws FileNotFoundException
* @throws IOException
* @throws XmlPullParserException
*/
public static String getVersion() throws FileNotFoundException, IOException, XmlPullParserException {
if (appVersion == null) {
String jarPath = VersionUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
jarPath = java.net.URLDecoder.decode(jarPath, "UTF-8");
try {
URL url = new URL("jar:file:" + jarPath + "!/META-INF/maven/com/loveU/pom.properties");
InputStream inputStream = url.openStream();
Properties properties = new Properties();
properties.load(inputStream);
appVersion = properties.getProperty("version");
} catch (Exception e) {
MavenXpp3Reader reader = new MavenXpp3Reader();
String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
if (isWindows() && basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
if (basePath.indexOf("/target/") != -1) {
basePath = basePath.substring(0, basePath.indexOf("/target/"));
}
Model model = reader.read(new FileReader(new File(basePath + "\\pom.xml")));
appVersion = model.getVersion();
}
}
return appVersion;
}
/**
* 是否是windows系统
*
* @return
*/
private static boolean isWindows() {
String osName = System.getProperty("os.name");
if (osName != null && osName.toLowerCase().indexOf("win") >= 0) {
return true;
}
return false;
}
}