Grain Academy (5) ---Maven from entry to enchantment

Preface

In our daily javaee project development, for the development and management of a large number of modules and the management of jar packages, we will inevitably design maven for project management. Here I summarize some of the more important knowledge points in Maven, which are also what I have learned recently. I feel the importance of using Maven in the project of Grain Academy, so I will summarize some of the more important knowledge points in Maven, hoping to provide some help for the learning partners.
"Finally, I hope my friends will leave a little love"

  1. preface

In our production environment, development is no longer a project for a project, but a project for each module, and the integration of multiple modules requires the use of a build tool such as Maven.

  1. Do we really need Maven?

Do you really need Maven? I believe my friends may ask themselves this question when they are learning Maven, what is Maven for? Why do we need to use Maven here? What trouble do we have without Maven? The reason why this question is raised is that even if we do not use Maven, we can still develop B/S structured projects. It's just more troublesome, just like when we travel? You don’t have to take a plane, we can also go by train, but the time efficiency is different.

There are mature solutions from presentation layer, business logic layer to persistence layer to database-we can also develop projects without using Maven.

image

There may be a misunderstanding in our thinking here. Maven is not directly used to assist coding, and his fighting position is not at the above levels. Therefore, it is necessary for us to find out which aspects are the shortcomings of our existing technology through the actual needs of enterprise development.

2.2 In the end, why use Maven?

Maven can help us improve development efficiency, but what problems can he help us solve?

①: Help us add third-party jar packages

         在我们今天企业的javaee开发领域中,有大量的第三方框架和工具可以供我们使用,要使用这些jar包最简单的方法就是复制粘贴到我们web工程下的WEB-INF/lib目录下。但是这会导致每次创建一个新的工程就需要将jar包重复复制到lib目录下,从而会造成我们的工作区间存在大量的重复文件,让我们的工程会显得很臃肿。

          而使用Maven后每个jar包本身值在本地创库中保存一份,需要jar包的工程只需要一坐标的方式简单的引用一下就可以了。不仅极大的节约了存储空间,让项目更加轻巧,更加避免了重复文件太多而造成的混乱。

②: Dependency between jar packages

          我们在开发工程的时候需要用的别的jar包,简而言之那别人在开发的时候也有可能需要使用到别的jar包,所以以此类推就会出现一种情况就是jar包依赖的情况。也及时我们的jar包不是孤立存在的,很多jar包都需要在其他jar包的支持下才能够正常工作,我们称之为jar包之间的依赖关系。其中比较典型的就是我们的文件上传操作,我们在使用commons-fileupload-1.3.jar 就依赖于 commons-io-2.0.1.jar,如果没有后面的包,我们的文件上传功能也就无法实现。

           那么问题来了,你知道你所使用的所有jar包依赖哪些包吗?当你拿到一个新的从未使用过jar包,你如何得知他需要那些jar包的支持?如果不了解情况的话,导入的jar包不够,那么现有的程序还是不能够正常运行。再进一步,当你的项目中需要用到上百的个jar包时,你还会人为的,手工的逐一确认他们一来的其他jar包吗?这简直就是一笔大工程。

           而引入Maven后,Maven就可以替我们自动的将当前jar包所依赖的其他所有jar包全部导入过来,无需人工参与,节约了我们大量的时间和精力。用实际的例子来说明就是:通过Maven导入commons-fileupload-1.3.jar 后,,commons-io-2.0.1.jar 会被自动导入,程序员不必了解这个依赖关系。

           下图就是spring所需jar包的部分依赖关系

image

③: Obtain a third-party jar package

          在javaee的开发中需要使用jar包种类繁多,几乎每个jar包在其本身的官网上获取方式都不尽相同。为了查找一个jar包我们需要找遍互联网,身心俱疲,没有经历过的人或许体会不到这种折磨。不仅如此,费劲心力找的jar包里有的时候并没有你需要的那个类,又或许有你要的类又没有你要的方法---以不规范的方式获取的jar包往往也是不规范的。

        使用maven我们可以享受到一个完全同意规范的jar包管理体系。你只需要在你的项目已坐标的方式依赖一个jar包,Maven就会自动从中央仓库进行下载,并同下载这个jar包所依赖的其他所有jar包------规范、完整、准确、一次性解决所有问题!

PS: Here, by the way, a unified specification can be said to be the highest belief of programmers. If there is no unified specification, it will mean that each specific technology has its own governance and needs to be added to our project in many different special ways; it will be incompatible with other technologies if it is finally joined, and it will be our development that suffers in the end. personnel. The uniform specification in any field can greatly reduce the programmer's work difficulty and reduce the workload. For example: the USB interface can be connected to various devices. If each device has its own unique interface, not only the manufacturer needs to maintain the design of each interface, but the user also needs to understand the interface corresponding to each device, which is undoubtedly very cumbersome .

④: Split the project into multiple engineering modules

     随着javaee项目的规模越来越大,开发团队的规模也与日俱增,一个项目上千人的团队持续开发很多对于javaee项目来说是再正常不过了。如果几百人上千人的开发项目是同一个web工程。那么架构师、项目经理该如何划分项目的模块、如何进行分工呢?这么大的项目已经不可能通过package结构来划分模块,必须将项目拆分成多个工程协同开发。多个模块工程中有的是java项目,有的是web项目。

     那么工程拆分后又该如何进行项目调和访问呢?这就需要用到maven的依赖管理机制。大家可以看一下survey调查项目的拆分情况。

image

3. Maven core explanation

3.1 Introduction to maven

       Maven是Apache软件基金会组织维护的一款自动化构建工具,专注服务于java平台的项目构建和项目依赖管理。Maven这个单词的本意是:“专家,内行”。

image

3.2 What is build

        构建并不是创建,创建一个工程并不等于构建一个项目。要了解构建的含义我们应该由浅入深的从以下三个层面来看:

①: Pure Java code

     小伙伴都知道,我们Java是一门编译型语言,纯Java扩展名的源文件需要编译成。class扩展名的字节码文件才能够执行。所以编写任何Java代码想要执行的话就必须编译成对应的.class文件

②: web project

      当我们需要通过浏览器访问java程序时就必须将包含java程序的web工程编译的结果“拿”到服务器上的指定目录下,并启动服务器才行。这个“拿”的工程我们叫部署。

     我们可以将未编译的web工程比喻成一只生的鸡,编译好的web工程是一只煮熟的鸡,编译部署的过程就是将鸡煮熟的过程。

  web工程和其编译结果的目录结构对比见下图:

image

③: Actual project

       在实际项目中整合第三方框架,web工程中除了Java程序和jsp页面、图片等静态资源之外,还包括第三方框架的jar包以及各种各样的配置文件。所有这些资源都必须按照正确的目录结构部署到服务器上,项目才可以运行。

       所以综上所述:构建就是以我们编写的java代码、框架配置文件、国家化等其他资源文件、jsp页面和图片等静态资源作为“原材料”,去“生产”一个可以运行的项目的过程。

     那么项目的构建过程包含哪些环节呢?

3.3 Several main links of the construction process

  • Cleanup: delete previous compilation results and prepare for recompilation
  • Compile: Compile the Java source program into an executable bytecode file.
  • Test: Test the key points in the project to ensure the correctness of the key points in the iterative development process of the project.
  • Report: Record and display the test results in a standard format after each test
  • Packaging: Package a project containing many files into a compressed file for installation or deployment. Jar package corresponding to java project, war package corresponding to web project
  • Installation: In the Maven environment, it specifically refers to installing the packaged result—jar package or war package into the local warehouse
  • Deployment: Deploy the packaged result to a remote warehouse or deploy the war package to the server to run.

3.4 Automated construction

In fact, we can find the corresponding operations in eclipse for the above links, but they are not standard. So since the IDE is ready to be built, why should we use a build tool like Maven? Let's look at a short story:

  这是阳光明媚的一天,托马斯像往常一样早早的来到公司,冲好了一杯咖啡,进入自己的邮箱---很不幸,QA小姐发来了一封邮件,报告了他昨天提交的模块测试结果--有bug。“好吧,反正也不是第一次”,托马斯摇摇头,进入IDE,运行自己的程序,编译打包。部署到服务器上,然后按照邮件中的操作路径进行测试。“嗯,没错,这个地方确实有问题”,托马斯说道。于是托马斯开始尝试修复这个bug,当他差不多有眉目的时候已经到了午饭的时间。
  下午继续工作,bug很快就被修正了,接着托马斯对模块重新进行了编译,打包、部署、测试之后确认没有问题了,回复了QA小姐的邮件。
  一天就这样过去了,明媚的阳光化作了美丽的晚霞,托马斯却觉得生活并不像晚霞那样美好。

Let’s sort out Thomas’ work this day
image

From this, we can find that a large part of Thomas’ time is spent on "compilation, packaging, deployment, and testing", these programmatic tasks, and the analysis problems and coding that really need to be realized by the wisdom of "people" only account for A very small part.

image

Can these programmed tasks be directly handed over to the machine for automatic completion? ----of course can! This is automated build

image

At this point, the significance of Maven is reflected. It can automatically execute from the beginning of the build process to the end:

image

3.5 Maven core concepts

        Maven能够实现自动化构建是和它的内部原理分不开的,这里我们从maven的九个核心概念入手,看看Maven是如何实现自动化构建的
  • POM
  • Conventional directory structure
  • coordinate
  • Dependency management
  • Warehouse management
  • Life cycle
  • Plugins and goals
  • inherit
  • polymerization

4 HOW

      Maven的核心程序中仅仅定义了抽象的生命周期,而具体的操作则是由Maven的插件来完成的,可是Maven的插件并不包含在Maven的核心程序中,在首次使用时需要联网下载。

5 Maven core concepts

5.1 POM

        Project Object Model:项目对象模型。将Java工程的相关信息封装为对象作为便于操作和管理的模型,Maven工程的核心配置,可以说是学习maven就是学习pom.xml文件中的配置。

5.2 Conventional directory structure

The agreed directory structure is an indispensable part for maven to achieve automated build. Take automated compilation, maven must be able to find the java source files before the next step can be compiled, and an accurate location must be maintained after compilation. The compiled bytecode file. During development, if we need to let third-party tools or frameworks know where the resources we created are located, there are basically two ways:

①: Tell it clearly in the form of configuration

②: Agreement based on third-party tools or frameworks

Maven's requirements for the project directory structure belong to the latter one.

image

 现在javaee开发领域普遍认同同一个观点:约定>配置>编码。意思就是能用配置解决的问题就不编码,能基于约定的就不进行配置。而Maven正是因为指定了特定文件保存的目录才能够对我们的java工程进行自动化构建。

5.3 Coordinates

①: Coordinates in geometry

  • Using the x and y vectors in a plane can uniquely determine a point in the plane.
  • Using x, y, z three vectors in space can uniquely determine a point in space

②: Maven's coordinates

Use the following three vectors to uniquely determine a Maven project in the maven warehouse

  • groupid: the domain name of the company or organization + the current project name
  • artifactld: the module name of the current project
  • version: the version of the current module

image

③: How to find the corresponding jar package in the warehouse by coordinates?

  • Connect the three vectors of gav

image

  • The connected string is searched in the warehouse as the directory structure

image

5.4 Dependence

  maven中最关键的部分,我们使用Maven最重要的就是使用他的依赖管理功能。要理解和掌握Maven的依赖管理,我们只需要解决一个  

      ①:依赖的目的是什么?

When A jar package uses some classes in B jar package, A has a dependency on B, which is a conceptual description. So how to introduce a jar package we need in a dependent way in the project?

  答案非常简单,就是使用depenency标签指定被依赖包的坐标就可以了。

image

        ②:依赖的范围

Everyone noticed that there is a scope setting in addition to the coordinates of the target jar package in the above dependency information, which is the scope of the dependency. There are several optional values ​​for the dependent range. What we get is: complie, test, and provided.

image

Combining specific examples: for helloFriend, hello is for the main program, and junit is for the test program. It is very obvious that the helloFriend main program needs hello, and the test program needs hello because it needs to call the main program, so the complie range dependency should be effective for both the main program and the test program.

  • Understand the difference between complie and provided from the two different stages of development and operation

image

     ③:有效性总结

image

    ④:依赖的传递性

A depends on B, B depends on C, can A use C? Then we have to see if the scope of B dependent C is complie, otherwise it is not available.

image

    依赖的排出

If we introduce a dependency of A in the current project, and A depends on B, then Maven will automatically introduce A dependent B into the current project, but in some cases, B may be an unstable version, or the current project Have adverse effects. This is how we can exclude B when referencing A.

  • Examples of scenarios

image

  • Configuration method

image

  • Effect after exclusion

image

5.5 Unified management of the version of the jar package it depends on

It is best to use the same version for a set of jar packages of the same framework. In order to facilitate the upgrade of the framework, the version information of the jar package can be extracted uniformly

  • Unified declaration version number

image

Where atguigu.spring.version is not a custom label

  • Refer to the previously declared version number

image

image

  • Other usage

image

5.5 Warehouse

①: Classification

    本地仓库:为当前本机电脑上的所有Maven工程服务

     远程仓库:私服:架构在当前局域网环境下,为当前局域网范围内的所有Maven工程服务。

image

Central warehouse: built on the internet, serving all Maven projects in the world

Mirror image of the central warehouse: set up on all continents to share traffic for the central warehouse. Reduce the pressure on the central warehouse and respond to user requests faster.

②: Documents in the warehouse

    maven的插件

    我们自己开发的项目的模块

    第三方框架或工具的jar包

Regardless of the jar package, the directory structure is generated in the warehouse according to the coordinates, so the dependencies can be queried in a unified way.

5.6 Life cycle

①: What is the cycle of Maven?

  • The Maven life cycle defines the execution order of each build link. With this list, Maven can automatically execute build commands.

  • Maven has three independent life cycles, namely:

      ①:clean  Lifecycle 在进行真正构建之前进行一些清理工作
    
      ②:Default Lifecycle 构建的核心部分,编译,测试,打包,安装,部署等等
    
      ③:site  Lifecycle 生成报告,站点,发布站点
    

They are independent of each other, you can just call clean to clean up the working directory, and only call site to generate the site. Of course, you can also directly run mvn clean install site to run all three sets of cycles.

Each life cycle consists of a set of stages, and the commands we usually enter on the command line always correspond to a specific stage. For example, running mvn clean, this clean is the clean life cycle, there is also a clean phase.

②: What cycle of clean

  clean生命周期一共包含三个阶段:

  ①:pre-clean 执行一些需要在clean之前完成的工作

  ②:clean 移除所有上一次构建生成的文件

  ③:post-clean执行一些需要在clean之后立刻生成的工作

③: site life cycle

   ①:pre-site 执行一些需要在生成站点文档之前完成的工作

   ②:site 生成项目的站点文档

   ③:post-site  执行一些需要在生成站点文档之后完成的工作,并且为部署做准备

   ④:site-deploy将生成的站点文档部署到特定的服务器上

The site phase and site-deploy phase are often used here to generate and publish Maven sites. This is a considerable function of maven. Manager prefers it. The automatic generation of documents and statistics is very beautiful.

④: Default life cycle

 Default生命周期是maven生命周期中最重要的一个,绝大部分工作都发生在这个生命周期中,这里,只解释一些比较重要和常用的阶段:

validate

generate-sources

process-sources

generate-resources

process-resources Copy and process resource files to the target directory, ready for packaging.

compile compile the source code of the project

process-classes

generate-test-sources

process-test-sources

generate-test-resources

process-test-resources Copy and process resource files to the target test directory.

test-compile compiles the test source code.

process-test-classes

test runs tests using a suitable unit testing framework. These test codes will not be packaged or deployed.

prepare-package

package Accept the compiled code and package it into a publishable format, such as JAR

pre-integration-test

integration-test

post-integration-test

verify

install installs the package to the local warehouse for other projects to depend on

deploy copies the final package to a remote warehouse so that other developers can share with the project or deploy to the server to run

⑤: Life cycle and automation construction

  运行任何一个阶段的时候,他前面的所有阶段都会被运行,例如我们运行mvn install的时候,代码会被编译,测试,打包。这就是Maven为什么能够自动执行构建过程的各个环节的原因。此外,Maven的插件机制是完全依赖Maven的生命周期的,因此理解生命周期是至关重要。

5.7 Plugins and targets

  • The core of Maven only defines the abstract life cycle, and specific tasks are completed by plugins
  • Each plug-in can implement multiple functions, and each function is a plug-in
  • Maven's life cycle and plugin goals are bound to each other to complete a specific build task

For example: compile is a goal of the plug-in maven-compli-plugin: pre-clean is a goal of the plug-in maven-clean-plugin.

5.8 Inheritance

①: Why do we need inheritance mechanism

Since non-complie dependent information cannot be passed in the "dependency chain", projects that need it can only be configured separately. E.g

image

image

At this time, if the project needs to unify the junit version of each module to 5.9, then manual modification of each project is undoubtedly very undesirable. Using the inheritance mechanism, such dependency information can be extracted to the parent project module for unified management.

②: Create parent project

Creating a parent project is the same as creating a general Java project. The only thing to note is that the packaging method should be set to pom at the beginning

③: Reference the parent project in the subproject

<parent>  
<!-- 父工程坐标 -->
  <groupId>...</groupId> 
  <artifactId>...</artifactId>  
  <version>...</version>  <relativePath>从当前目录到父项目的 pom.xml 文件的相对路径</relativePath> </parent>

image

At this time, if the groupid and version of the subproject are duplicates of the parent project, they can be deleted.

④: Manage dependencies in the parent project

Enclose the dependencies tag in the parent project with the dependencyManagement tag

image

image

Re-specify the required dependencies in the sub-project, delete the scope and version number

image

5.9 Aggregation

①: Why use aggregation?

After splitting multiple projects into modules, you need to manually install them to the warehouse one by one before the dependencies can take effect. After modifying the source code, you also need to manually perform the clean operation one by one. After using aggregation, you can install and clean up Maven projects in batches.

②: How to configure aggregation?

Use the combination of moudles/module tags in the total aggregation project and specify the relative path of the module project.

image

6 Summary

Maven is mainly a management mechanism for project management and jar packages. Friends can go to http://mvnrepository.com/ to search for required jar package dependency information.

Guess you like

Origin blog.csdn.net/qq_44762290/article/details/107504262