Introduction to Project Jigsaw – 拼图项目简介

最后修改: 2017年 3月 24日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

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
  • and its implementation in JDK source and Java runtime

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

2.模块化

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

2.1.模块化单元

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:

JARs确实有助于将相关的组件组合在一起,但它们确实有一些限制。

  • explicit contracts and dependencies between JARs
  • weak encapsulation of elements within the JARs

2.2. JAR Hell

2.2 JAR地狱

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.

JARs还有一个问题–JAR地狱。躺在classpath上的多个版本的JARs,导致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.

JVM使用classpath的另一个问题是,应用程序的编译会成功,但应用程序在运行时将以ClassNotFoundException失败,原因是在运行时classpath上缺少JARs。

2.3. New Unit of Modularity

2.3.模块化的新单元

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规划了一个全新的模块化系统。

3. Project Jigsaw

3.拼图项目

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
  • modularize the JDK libraries – implemented under JEP 200
  • 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

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.

另一个重要的举措是封装JDK中的内部API,那些在sun.*包下的API和其他非标准的API。这些API从来都不是为了给公众使用的,也没有计划要维护。但这些API的力量使Java开发者在开发不同的库、框架和工具时利用了它们。有一些内部API被替换掉了,其他的则被移到了内部模块中。

4. New Tools for Modularity

4.模块化的新工具

  • 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
  • jdeprscan – helps in analyzing the code base for usage of any deprecated APIs
  • jlink – helps in creating a smaller runtime by combining the application’s and the JDK’s modules
  • 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

5. Module System Architecture

5.模块系统结构

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.

在语言中实现的模块系统支持这些模块,就像包一样,是一种顶层结构。开发人员可以将他们的代码组织成模块,并在各自的模块定义文件中声明它们之间的依赖关系。

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.readercom.baeldung.writer。每个模块的定义都在module-info.java中指定,代码文件分别放在com/baeldung/readercom/baeldung/writer中。

5.1. Module Definition Terminologies

5.1 模块定义的术语

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>
  • 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
  • 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

6. Simple Modular Application

6.简单的模块化应用

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

让我们创建一个简单的模块化应用程序,其模块和它们的依赖关系如下图所示。

project jigsaw baeldung module graph

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是根模块。它定义了模型类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模块提供了一个接口com.baeldung.student.service.StudentService,具有抽象的CRUD操作。

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

7.编译和运行样本

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平台上编译和运行上述模块的脚本。这些可以在core-java-9项目中找到这里。在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取消了classpath的概念,转而引入了模块路径。这个路径是可以发现模块的位置。

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

8.应用于JDK源代码的模块系统

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 API 的代码库。如果你解压该归档文件,你会发现有多个文件夹,其中少数以java开始,少数以javafx开始,其余以jdk开始。每个文件夹代表一个模块。

jdk9-src

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模块的依赖关系图为。

jdk-tr1

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

9.结论

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创建更小的运行时,以及创建模块化的jars等功能。我们将在以后的文章中详细介绍这些功能。

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.

拼图项目是一个巨大的变化,我们将不得不等待和观察它如何被开发者生态系统接受,特别是与工具和库创建者。

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

本文中使用的代码可以在GitHub上找到over