Introduction to Project Jigsaw

原文地址:https://www.baeldung.com/project-jigsaw-java-modularity

以下中文翻译为作者根据自己的理解+Google+YouDao作为参考翻译而得,存在偏颇之处请读者查看对应原文,自行理解。

1. Introduction

Project Jigsaw is an umbrella project with the new features aimed at two aspects:

Project Jigsaw 作为一个大项目包含以下两个方面的新特性:

  • the introduction of module system in the Java language
  • 在Java中引入模块系统
  • and its implementation in JDK source and Java runtime
  • 以及JDK源码和Java运行环境的具体实现

In this article, we'll introduce you to the Jigsaw project and its features and finally wrap it up with a simple modular application.

本文中,我们将介绍Jigsaw及其一些特性,并且通过一个简单的模块化应用来入门。

2. Modularity

Simply put, modularity is a design principle that helps us to achieve:

简单而言,模块化是一种帮助我们完成编码的设计原则:

  • loose coupling between components
  • 减小组件之间的耦合度
  • clear contracts and dependencies between components
  • 明确组件之间的联系和依赖关系
  • hidden implementation using strong encapsulation
  • 通过强封装隐藏具体实现

2.1. Unit of Modularity

Now comes the question as to what is the unit of modularity? In the Java world, especially with OSGi, JARs were considered as the unit of modularity.

什么是模块化单元?在Java中,尤其是OSGi,JAR就被认为是模块化单元。

JARs did help in grouping the related components together, but they do have some limitations:

JAR确实有利于将相关组件组合在一起,但同时也带来了一些问题:

  • explicit contracts and dependencies between JARs
  • 强化了Jar之间的联系及依赖关系
  • weak encapsulation of elements within the JARs
  • 弱化了Jar中代码的封装性

2.2. Jar hell

There was another problem with JARs – the JAR hell. Multiple versions of the JARs lying on the classpath, resulted in the ClassLoader loading the first found class from the JAR, with very unexpected results.

Jar还存在一个问题:JAR hell。若类路径上存在多个版本的JAR,会导致ClassLoader从JAR中加载第一个找到的类,这会导致一些问题。

The other issue with the JVM using classpath was that the compilation of the application would be successful, but the application will fail at runtime with the ClassNotFoundException, due to the missing JARs on the classpath at runtime.

使用classpathJVM存在另一个问题是,应用程序的编译虽然成功,但应用程序在运行时才会报错ClassNotFoundException,原因是在运行时类路径上缺少jar。

2.3. New Unit of Modularity

With all these limitations, when using JAR as the unit of modularity, the Java language creators came up with a new construct in the language called modules. And with this, there is a whole new modular system planned for Java.

由于目前使用JAR作为模块化单元存在以上这些问题,Java团队在Java中加入了一种新的构建方式,被称为modules,这将为Java带来全新的模块化系统。

3. Project Jigsaw

The primary motivations for this project are:

该项目的宗旨为:

  • create a module system for the language – implemented under JEP 261
  • 为语言创建模块化系统
  • apply it to the JDK source – implemented under JEP 201
  • 将其在JDK source中得到应用
  • modularize the JDK libraries – implemented under JEP 200
  • 模块化JDK依赖库
  • update the runtime to support modularity – implemented under JEP 220
  • 更新运行时环境以支持模块化
  • be able to create smaller runtime with a subset of modules from JDK – implemented under JEP 282
  • 能够从JDK的子模块中构建一个小型的运行时环境

Another important initiative is to encapsulate the internal APIs in the JDK, those who are under the *sun.** packages and other non-standard APIs. These APIs were never meant to be used by public and were never planned to be maintained. But the power of these APIs made the Java developers leverage them in the development of different libraries, frameworks, and tools. There have been replacements provided for few internal APIs and the others have been moved into internal modules.

另一个重要的举措是将*sun.*下面的包和一些非标准的APIs封装到JDK中。这些api从来没有打算对外公众使用,也不打算维护这些它。由于这些APIs的强大功能使得其在开发时仍然在使用,我们已为少数APIs提供了替代品,其余APIs已经转移到jdk.internal*中。

4. New Tools for Modularity

  • jdeps – helps in analyzing the code base to identify the dependencies on JDK APIs and the third party JARs. It also mentions the name of the module where the JDK API can be found. This makes it easier in modularizing the code base.(帮助分析代码库以识别 JDK API 和第三方 JAR 上的依赖关系。 它还提到了可以找到JDK API的模块的名称,这使得模块化代码基础更容易。)
  • jdeprscan – helps in analyzing the code base for usage of any deprecated APIs.(帮助分析使用了任何已弃用API的代码库)
  • jlink – helps in creating a smaller runtime by combining the application's and the JDK's modules.(通过组合应用程序和JDK的模块,帮助创建较小的jre。)
  • jmod – helps in working with jmod files. jmod is a new format for packaging the modules. This format allows including native code, configuration files, and other data that do not fit into JAR files.(帮助构建jmod文件。 JMOD是一种用于打包模块的新格式。 此格式允许包括本机代码,配置文件和不适合JAR文件的其他数据。)

5. Module System Architecture

The module system, implemented in the language, supports these as a top level construct, just like packages. Developers can organize their code into modules and declare dependencies between them in their respective module definition files.

在语言中实现的模块系统支持它们作为top level construct,就像package一样。 开发人员可以将其代码组织到模块中,并在各自的模块定义文件中声明它们之间的依赖关系。

A module definition file, named as module-info.java, contains:

模块的定义文件,名称叫module-info.java,包含如下内容:

  • its name 模块名
  • the packages it makes available publicly 可以对外公开的包
  • the modules it depends on 模块的依赖项
  • any services it consumes 可以消费的其他服务
  • any implementation for the service it provides 提供服务接口的现实

The last two items in the above list are not commonly used. They are used only when services are being provided and consumed via the java.util.ServiceLoader interface.

上面列表中的最后两点不常用。 通常只在java.util.serviceloader接口提供和消费服务时使用它们。

A general structure of the module looks like:

通常一个模块结构类似这样:

src
|----com.baeldung.reader
| |----module-info.java
| |----com
| |----baeldung
| |----reader
| |----Test.java
|----com.baeldung.writer
|----module-info.java
|----com
|----baeldung
|----writer
|----AnotherTest.java

The above illustration defines two modules: com.baeldung.reader and com.baeldung.writer. Each of them has its definition specified in module-info.java and the code files placed under com/baeldung/reader and com/baeldung/writer, respectively.

上述结构中定义了两个模块: com.baeldung.reader 和 _com.baeldung.writer_。他们都包含了module-info.java并且分别位于com/baeldung/readercom/baeldung/writer

5.1. Module Definition Terminologies

Let us look at some of the terminologies; we will use while defining the module (i.e., within the module-info.java):

我们先来了解一些在定义模块时会使用到的术语(在module-info.java中使用):

  • module: the module definition file starts with this keyword followed by its name and definition.(模块定义文件以这个关键字开始,后面跟着它的名称和定义。)
  • requires: is used to indicate the modules it depends on; a module name has to be specified after this keyword.(用于指示它所依赖的模块;必须在关键字之后指定模块名)
  • transitive: is specified after the requires keyword; this means that any module that depends on the module defining requires transitive <modulename> gets an implicit dependence on the <modulename>.(在requires关键字后面指定;这意味着任何依赖于模块定义的模块都需要传递 <modulename> 得到对 <modulename> 的隐式依赖 <modulename> 。)
  • exports: is used to indicate the packages within the module available publicly; a package name has to be specified after this keyword.(用于指示模块内的包是公开可用的;包名必须在这个关键字之后指定)
  • opens: is used to indicate the packages that are accessible only at runtime and also available for introspection via Reflection APIs; this is quite significant to libraries like Spring and Hibernate, highly rely on Reflection APIs; opens can also be used at the module level in which case the entire module is accessible at runtime.(用于指示仅在运行时可访问的包,也可通过反射APIs进行自省;这对于像Spring和Hibernate这样高度依赖反射api的库来说是非常重要的;opened 也可以在模块级别使用,在这种情况下,整个模块在运行时是可访问的)
  • uses: is used to indicate the service interface that this module is using; a type name, i.e., complete class/interface name, has to specified after this keyword.(用于指示该模块正在使用的服务接口;类型名称,即完整的类/接口名称,必须在关键字之后指定)
  • provides … with ...: they are used to indicate that it provides implementations, identified after the with keyword, for the service interface identified after the provides keyword.(用于指定在with关键字提供的实现;在providers关键字后提供服务接口)

6. Simple Modular Application

Let us create a simple modular application with modules and their dependencies as indicated in the diagram below:

让我们创建一个简单的模块化应用程序,其中模块及其依赖项如下图所示:

img

The com.baeldung.student.model is the root module. It defines model class com.baeldung.student.model.Student, which contains the following properties:

com.baeldung.student.model是根模块。它定义了model class _com.baeldung.student.model.student_,其中包含以下属性:

public class Student {
private String registrationId;
//other relevant fields, getters and setters
}

It provides other modules with types defined in the com.baeldung.student.model package. This is achieved by defining it in the file module-info.java:

它提供了在com.baeldung.student.model包中定义的类型的其他模块。 这是通过在文件module-info.java中定义它来实现的:

module com.baeldung.student.model {
exports com.baeldung.student.model;
}

The com.baeldung.student.service module provides an interface com.baeldung.student.service.StudentService with abstract CRUD operations:

com.baeldung.student.service模块提供了抽象的CRUD操作的 com.baeldung.student.service.StudentService 接口。

public interface StudentService {
public String create(Student student);
public Student read(String registrationId);
public Student update(Student student);
public String delete(String registrationId);
}

It depends on the com.baeldung.student.model module and makes the types defined in the package com.baeldung.student.service available for other modules:

它依赖于com.baeldung.student.model模块,并使com.baeldung.student.service中定义的类可以在其他模块中使用:

module com.baeldung.student.service {
requires transitive com.baeldung.student.model;
exports com.baeldung.student.service;
}

We provide another module com.baeldung.student.service.dbimpl, which provides the implementation com.baeldung.student.service.dbimpl.StudentDbService for the above module:

我们提供另一个模块 com.baeldung.student.service.dbimpl, 以及上述模块的实现com.baeldung.student.service.dbimpl.StudentDbService

public class StudentDbService implements StudentService {

public String create(Student student) {
// Creating student in DB
return student.getRegistrationId();
}

public Student read(String registrationId) {
// Reading student from DB
return new Student();
}

public Student update(Student student) {
// Updating student in DB
return student;
}

public String delete(String registrationId) {
// Deleting student in DB
return registrationId;
}
}

It depends directly on com.baeldung.student.service and transitively on com.baeldung.student.model and its definition will be:

他直接依赖于com.baeldung.student.service,间接依赖于com.baeldung.student.model,其定义如下:

module com.baeldung.student.service.dbimpl {
requires transitive com.baeldung.student.service;
requires java.logging;
exports com.baeldung.student.service.dbimpl;
}

The final module is a client module – which leverages the service implementation module com.baeldung.student.service.dbimpl to perform its operations:

最后一个模块使客户端模块,它利用实现服务的模块com.baeldung.student.service.dbimpl来完成其操作:

public class StudentClient {
public static void main(String[] args) {
StudentService service = new StudentDbService();
service.create(new Student());
service.read("17SS0001");
service.update(new Student());
service.delete("17SS0001");
}
}

And its definition is:

其定义如下:

module com.baeldung.student.client {
requires com.baeldung.student.service.dbimpl;
}

7. Compiling and Running the Sample

We have provided scripts for compiling and running the above modules for the Windows and the Unix platforms. These can be found under the core-java-9 project here. The order of execution for Windows platform is:

我们提供了在Windows和Unix平台编译和运行一下模块的脚本。以下为Windows平台的执行顺序:

  1. compile-student-model
  2. compile-student-service
  3. compile-student-service-dbimpl
  4. compile-student-client
  5. run-student-client

The order of execution for Linux platform is quite simple:

Linux平台的执行顺序更加简单:

  1. compile-modules
  2. run-student-client

In the scripts above, you will be introduced to the following two command line arguments:

在上面的脚本中,将向您介绍以下两个命令行参数:

  • –module-source-path
  • –module-path

Java 9 is doing away with the concept of classpath and instead introduces module path. This path is the location where the modules can be discovered.

Java 9抛弃了类路径的概念,取而代之的是引入了模块路径。该路径可以发现模块的位置。

We can set this by using the command line argument: --module-path.

我们可以通过使用*--module-path*命令行参数来进行设置。

To compile multiple modules at once, we make use of the –module-source-path. This argument is used to provide the location for the module source code.

为了一次编译多个模块,我们使用*--module-source-path*。此参数用于提供模块源代码的位置。

8. Module System Applied to JDK Source

Every JDK installation is supplied with a src.zip. This archive contains the code base for the JDK Java APIs. If you extract the archive, you will find multiple folders, few starting with java, few with javafx and the rest with jdk. Each folder represents a module.

每个JDK安装都提供了一个src.zip。该归档文件包含JDK Java APIs的代码库。如果您提取归档文件,您会发现多个文件夹,一些以java开头的,一些以javafx开头的,其余的都以jdk开头。每个文件夹代表一个模块。

img

The modules starting with java are the JDK modules, those starting with javafx are the JavaFX modules and others starting with jdk are the JDK tools modules.

java开头的模块为JDK模块,以javafx开头的模块为javafx模块,以jdk开头的模块为JDK工具模块。

All JDK modules and all the user defined modules implicitly depend on the java.base module. The java.base module contains commonly used JDK APIs like Utils, Collections, IO, Concurrency among others. The dependency graph of the JDK modules is:

所有JDK模块和所有用户定义的模块都隐式依赖于java.base模块。java.base模块包含常用的JDK APIs,如Utils、Collections、IO、Concurrency等。JDK模块的依赖关系图如下:

img

You can also look at the definitions of the JDK modules to get an idea of the syntax for defining them in the module-info.java.

您还可以查看JDK模块的定义,以了解在module-info.java中定义它们的语法。

9. Conclusion

In this article, we looked at creating, compiling and running a simple modular application. We also saw how the JDK source code had been modularized.

在本文中,我们讨论了如何创建、编译和运行一个简单的模块化应用程序。我们还了解了JDK源代码是如何模块化的。

There are few more exciting features, like creating smaller runtime using the linker tool – jlink and creating modular jars among other features. We will introduce you to those features in details in future articles.

还有一些更令人兴奋的特性,比如使用链接器工具jlink创建更小的运行环境,以及使用其他特性创建模块化jar。我们将在以后的文章中详细介绍这些特性。

Project Jigsaw is a huge change, and we will have to wait and watch how it gets accepted by the developer ecosystem, in particular with the tools and library creators.

Jigsaw项目带来的巨变化,我们将不得不等待并观察它如何被开发者所接受,特别是工具和库的创造者。

The code used in this article can be found over on GitHub.