小编最近工作有点小忙,一直没有更新博客,今天组里的技术大佬让小编share一下关于maven的相关知识,小编着实一慌,毕竟对后台开发不感冒的小编来说 太!难!了!为了明天不丢人,趁着下班,赶紧把明天希望分享的内容梳理一下,也顺便学习一下Gradle的内容
一.Dependencies
1.repositories
- maven
- Maven维护了一个中央仓库(repo1.maven.org),所有第三方库将自身的jar以及相关信息上传至中央仓库,Maven就可以从中央仓库把所需依赖下载到本地
- Maven并不会每次都从中央仓库下载jar包。一个jar包一旦被下载过,就会被Maven自动缓存在本地目录,所以,除了第一次编译时因为下载需要时间会比较慢,后续过程因为有本地缓存,并不会重复下载相同的jar包。
- artifactory
- Artifactory是一款Maven仓库服务端软件,可以用来在内网搭建maven仓库,供公司内部公共库的上传和发布,以提高公共代码使用的便利性
2.dependencies
- api - Api 配置应该用于声明由库 API 导出的依赖项,出现在 api 配置中的依赖项将传递性地向库的使用者公开,因此将出现在使用者的编译类路径中
- implementation - 实现配置应该用于声明组件内部的依赖项,在实现配置中发现的依赖项不会向使用者公开,因此不会泄漏到使用者的编译类路径中 【依赖关系不再泄漏到使用者的编译类路径中,因此您永远不会意外地依赖于可传递的依赖关系 / 由于减少了类路径大小,编译速度更快 / 实现依赖关系发生变化时重新编译的次数更少: 不需要重新编译使用者 / Pom发布的内容更少】尽可能使用implementation配置而不是 api
- 那么什么时候应该使用 api 配置呢? Api 依赖关系是指在库二进制接口中至少包含一种类型的依赖关系,通常称为它的 ABI (应用二进制接口)
- 超类或接口中使用的类型
- 在公共方法参数中使用的类型,包括泛型参数类型(其中 public 是编译器可见的内容)
- 在公共场所使用的类型
- 公共注释类型
- 使用implementation
- 方法体中专用的类型
- 专门用于私人成员的类型
- 类型只存在于内部类中
- 那么什么时候应该使用 api 配置呢? Api 依赖关系是指在库二进制接口中至少包含一种类型的依赖关系,通常称为它的 ABI (应用二进制接口)
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class HttpClientWrapper {
private final HttpClient client; // private member: implementation details
// HttpClient is used as a parameter of a public method
// so "leaks" into the public API of this component
public HttpClientWrapper(HttpClient client) {
this.client = client;
}
// public methods belongs to your API
public byte[] doRawGet(String url) {
HttpGet request = new HttpGet(url);
try {
HttpEntity entity = doGet(request);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toByteArray();
} catch (Exception e) {
ExceptionUtils.rethrow(e); // this dependency is internal only
} finally {
request.releaseConnection();
}
return null;
}
// HttpGet and HttpEntity are used in a private method, so they don't belong to the API
private HttpEntity doGet(HttpGet get) throws Exception {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.err.println("Method failed: " + response.getStatusLine());
}
return response.getEntity();
}
}
- runtimeOnly - 声明运行时依赖项,而不是在编译时需要的依赖项。
- providedRuntime \ providedCompile - 这两个配置的作用域与各自的compile和runtime配置相同,只是它们没有添加到 WAR的archive中
- strictly - 任何版本不匹配此版本符号将被排除。 这是最强的版本声明。
- test - 编译Test时需要用到该jar包 Junit
二.Specific Using
1.io.spring.dependency-management
- Spring开发了一个类似Maven的依赖关系管理功能的Gradle插件,使用插件可以进行依赖项管理
- 使用插件的DSL来直接配置依赖项
- 导入一个或者多个已经存在的Maven bom文件
2.archivesBaseName \ group
- group相当于groupId 域.公司名.组名
- archivesBaseName相当于artifactId 项目名
3.avoid duplicate dependencies in the sub project
- 提到一个common中并在子项目中引入common依赖