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>

maven-dependencies插件的模拟实现的更多相关文章

  1. maven常用插件pom配置

    一.问题描述: 部署一个maven打包项目时,jar包,依赖lib包全部手动上传至服务器,然后用maven部署报错:Exception in thread "main" java. ...

  2. 自己动手编写Maven的插件

    Maven的插件机制是完全依赖Maven的生命周期的,因此理解生命周期至关重要.本文参考官方文档后使用archetype创建,手动创建太麻烦. 创建创建项目 选择maven-archetype-moj ...

  3. 13 Maven 编写插件

    Maven 编写插件 Maven 的任何行为都是由插件完成的,包括项目的清理.绵编译.测试以及打包等操作都有其对应的 Maven 插件.每个插件拥有一个或者多个目标,用户可以直接从命令行运行这些插件目 ...

  4. maven项目在myeclipse中不出现Maven Dependencies 和maven标识的解决方法

    这种情况通常出现在 我们新加载了一个 maven的项目,但是myeclipse没识别到. 或者说 我们把该项目修改成了maven项目--------也就是说该项目 有了pom.xml 但是还没有mav ...

  5. (转)淘淘商城系列——使用maven tomcat插件启动聚合工程

    http://blog.csdn.net/yerenyuan_pku/article/details/72672389 上文我们一起学习了如何使用maven tomcat插件来启动web工程,本文我们 ...

  6. (转)淘淘商城系列——使用maven tomcat插件启动web工程

    http://blog.csdn.net/yerenyuan_pku/article/details/72672138 上文我们一起学习了怎样搭建maven工程,这篇文章我就来教大家一起学习怎样用to ...

  7. 【maven】插件和依赖管理

    1.插件管理 定义 pluginManagement 用来做插件管理的.它是表示插件声明,即你在项目中的pluginManagement下声明了插件,Maven不会加载该插件,pluginManage ...

  8. 【01】Maven依赖插件之maven-dependency-plugin

    一.插件目标(goal) 1.analyze:分析项目依赖,确定哪些是已使用已声明的,哪些是已使用未声明的,哪些是未使用已声明的 2.analyze-dep-mgt:分析项目依赖,列出已解析的依赖项与 ...

  9. Maven 的插件和生命周期的绑定

    一.Maven 的生命周期 Maven 的生命周期是对所有的构建过程进行抽象和统一.Maven 的生命周期是抽象的,这意味着生命周期本身不做任何实际的工作,生命周期只是定义了一系列的阶段,并确定这些阶 ...

  10. 【转】Maven Jetty 插件的问题(css/js等目录死锁)的解决

    Maven Jetty 插件的问题(css/js等目录死锁,不能自动刷新)的解决:   1. 打开下面的目录:C:\Users\用户名\.m2\repository\org\eclipse\jetty ...

随机推荐

  1. 【C#】学习笔记(1) Delegates,Events,Lambda Expressions

    C#是跟着杨老师的教程走的,在这里感谢一下老师的无私奉献,他的cnblog地址:>cgzl,他的B站地址:>solenovex. 进入正题: Delegate表示委托,委托是一种数据结构, ...

  2. Android 矢量图详解

    官方文档 关于 Vector,在官方开发指南中介绍.本文章是由个人翻译官方指南然后添加个人理解完成. 由于个人精力有限,多个渠道发布,排版上可能会有问题,如果影响查看,请移步 Android 开发者家 ...

  3. BayaiM__linux双网卡绑定文档

    BayaiM__linux双网卡绑定文档 开门贱山:以下内容纯属原创,如有雷同,爱咋咋滴吧~~!!—————————————————————————————————————————— 1,备份网卡信息 ...

  4. redis删除策略

    redis 设置过期时间 Redis 中有个设置时间过期的功能,即对存储在 redis 数据库中的值可以设置一个过期时间.作为一个缓存数据库,这是非常实用的.如我们一般项目中的 token 或者一些登 ...

  5. [视频教程] ubuntu系统下以守护进程方式安装使用Redis

    直接访问redis的中国官网,在下载部分,可以看到安装和使用的方式.wget http://download.redis.io/releases/redis-5.0.4.tar.gztar xzf r ...

  6. C学习笔记(5)--- 指针第二部分,字符串,结构体。

    1. 函数指针(function pointer): 函数指针是指向函数的指针变量. 通常我们说的指针变量是指向一个整型.字符型或数组等变量,而函数指针是指向函数. 函数指针可以像一般函数一样,用于调 ...

  7. 5. this关键字

    一.this关键字概述 1. this作为对象的引用,它总是指向调用该方法的对象 2. this的最大作用:让类中的一个方法访问该类中的另一个方法或实例变量 二.this关键字的两种用法 1. 在方法 ...

  8. 多线程时,请求执行不是按顺序的,可添加Critical Section Controller(临界部分控制器),执行顺序是固定的,但执行一段时间后,该逻辑器下的请求不再循环,无解ing

  9. (转)cube-ui后编译

    转载地址:https://www.jianshu.com/p/189755f9ce43 1. 后编译介绍 目前大部分的前端项目开发都是使用es6+的代码并且使用babel进行编译,而传统的对代码包的引 ...

  10. day58_9_24多对多建表手动,form组件(判断类型),cookies和session

    一.多对多建表关系之手动添加. 1.全自动 像之前讲过的一样,我们可以通过manytomanyField的字段来建立多对多关系: class Book(models.Model): title = m ...