maven-dependencies插件的作用就是从本地的maven仓库中提取jar包,放到某个文件夹下面。这个功能其实是很简单的。

我在一家银行工作时,公司电脑都无法连外网,所以无法通过maven下载jar包。但是在公司电脑上开发时,我又想使用maven进行编译、打包等操作。如果把我电脑上的maven仓库复制上去,太大,我想根据pom.xml只复制那些项目实际用到的jar包,形成maven仓库。

首先需要进行如下配置

targetDir=jars
#always use / ranther than \\
pom=C:/Users/weidiao/Desktop/pabqa/pom.xml
m2=C:/Users/weidiao/.m2
#should put all jars together ?
simple=true

targetDir表示从本地maven仓库中复制到哪里去,pom表示pom.xml的路径,simple表示是否保留maven的目录结构。如果simple=true,则不保留目录结构,只复制jar包;如果simple=false,则遵循maven仓库的目录格式。

下面的代码根据pom.xml从本地的maven仓库中复制信息到一个新的文件夹

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* 给定本地maven仓库
* pom.xml文件
*/
public class MavenJarExtractor {
static class Dependency {
String artifactId;
String groupId;
String version; public String getArtifactId() {
return artifactId;
} public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
} public String getGroupId() {
return groupId;
} public void setGroupId(String groupId) {
this.groupId = groupId;
} public String getVersion() {
return version;
} public void setVersion(String version) {
this.version = version;
} public Path getPath() {
return Paths.get(getGroupId().replace('.', '/'))
.resolve(Paths.get(getArtifactId()))
.resolve(getVersion());
} public String getFileName() {
return getArtifactId() + "-" + getVersion();
}
} static class CopyTask {
Path src;
Path des; public Path getSrc() {
return src;
} public void setSrc(Path src) {
this.src = src;
} public Path getDes() {
return des;
} public void setDes(Path des) {
this.des = des;
}
} String reFirst(String pattern, String s, int group) {
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(s);
boolean found = matcher.find();
if (found) {
return matcher.group(group);
} else return null;
} void createDir(Path p) throws IOException {
p = p.toAbsolutePath();
if (Files.notExists(p)) {
if (Files.notExists(p.getParent()))
createDir(p.getParent());
Files.createDirectory(p);
}
} void copyFolder(Path src, Path des, boolean simple) {
try {
Files.list(src).forEach(x -> {
if (simple && !x.getFileName().toString().endsWith(".jar"))
return;
try {
Files.copy(x, des.resolve(x.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
} List<Dependency> parseDom(String pomPath) throws IOException {
//解析pom=解析属性+解析dependency
Document dom = Jsoup.parse(Paths.get(pomPath).toFile(), "utf8");
Element p = dom.selectFirst("properties");
Map<String, String> properties = new HashMap<>();
if (p != null) {
Elements ps = p.children();
for (Element i : ps) {
properties.put(i.tagName(), i.text());
}
}
List<Dependency> dependencyList = new ArrayList<>();
for (Element dep : dom.select("dependency")) {
Dependency dependency = new Dependency();
dependencyList.add(dependency);
dependency.setArtifactId(dep.getElementsByTag("artifactId").text());
dependency.setGroupId(dep.getElementsByTag("groupId").text());
dependency.setVersion(dep.getElementsByTag("version").text());
if (dependency.getVersion().matches("\\$\\{.+\\}")) {
String version = reFirst("\\$\\{(.+)\\}", dependency.getVersion(), 1);
dependency.setVersion(properties.get(version));
}
}
return dependencyList;
} List<CopyTask> buildTask(List<Dependency> dependencyList, String m2, String targetDir, boolean simple) {
//定义任务列表
List<CopyTask> tasks = new ArrayList<>();
for (Dependency i : dependencyList) {
Path depDir = Paths.get(m2).resolve("repository").resolve(i.getPath());
if (Files.notExists(depDir)) {
throw new RuntimeException("没有在 "+depDir+" 找到" + i.getGroupId() + " " + i.getArtifactId());
}
CopyTask task = new CopyTask();
task.setSrc(depDir);
if (simple) {
task.setDes(Paths.get(targetDir));
} else {
task.setDes(Paths.get(targetDir).resolve("repository").resolve(i.getPath()));
}
tasks.add(task);
}
System.out.println(JSON.toJSONString(tasks, true));
return tasks;
} void executeTask(List<CopyTask> tasks, boolean simple) throws IOException {
//执行任务
for (CopyTask task : tasks) {
if (Files.notExists(task.des)) {
createDir(task.des);
}
copyFolder(task.getSrc(), task.getDes(), simple);
}
System.out.println("task over successfully");
} MavenJarExtractor(String targetDir, String pom, String m2, boolean simple) throws IOException {
List<Dependency> dependencies = parseDom(pom);
List<CopyTask> tasks = buildTask(dependencies, m2, targetDir, simple);
executeTask(tasks, simple);
} public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
//加载配置
Properties config = new Properties();
config.load(new InputStreamReader(new FileInputStream("mavenjar.properties")));
String targetDir = config.getProperty("targetDir", "target");
String m2 = config.getProperty("m2", Paths.get(System.getProperty("user.home")).resolve(".m2").toString());
String pomPath = config.getProperty("pom");//"C:\\Users\\weidiao\\Desktop\\pabqa\\pom.xml";
boolean simple = Boolean.parseBoolean(config.getProperty("simple"));
MavenJarExtractor extractor = new MavenJarExtractor(targetDir, pomPath, m2, simple);
}
}

需要依赖的jar包如下所示:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>wyf</groupId>
<artifactId>mavenjar</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <dependencies>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>MavenJarExtractor</mainClass>
</manifest>
</archive>
<finalName>mavenjar</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

最新文章

  1. Linux NFS服务器的安装与配置
  2. 全局变量 HInstance 到底是在什么时候赋值的?
  3. Java--JDK动态代理核心源码解析
  4. Ubuntu上安装MySql过程,以及遇到的一些问题
  5. 利用grep命令查找文件内容
  6. IOC(控制反转和依赖注入)之Autofac
  7. Linux Shell编程(18)—— 循环控制
  8. 浅谈:配置本地yum源(centos)
  9. JavaWEB开发国际化
  10. 基于php(Thinkphp)+jquery 实现ajax多选,反选,不选 删除数据 新手学习向
  11. java中的内存溢出和内存泄漏
  12. linux 命令ls
  13. Django--ORM相关操作
  14. Leetcode 600 不含连续1的非负整数
  15. C\C++学习笔记 1
  16. python-中缀表达式转前缀表达式
  17. Codeforces 861D - Polycarp&#39;s phone book 【Trie树】
  18. python实现定时发送系列
  19. LA 2963 超级传输(扫描)
  20. net与树莓派的情缘-安装SVN(三)

热门文章

  1. jsp表单更新数据库
  2. 一文解读ITIL (转)
  3. python从入门到放弃之线程篇
  4. 获取SpringCloud gateway响应的response的值,记录踩坑
  5. 错误:shell 打开出现一大堆 错误 declare -x 之类的消息
  6. C# 集合的交集 差集 并集 去重
  7. java的加载与运行
  8. pip 源切换至国内镜像
  9. leetcode279. 完全平方数
  10. Sharding-JDBC:查询量大如何优化?