Knowledge and simple use of maven

Simple use of maven

 

1. Background of the use of maven

Maven is a mature project management tool. Its core concept is the POM (Project Object Model) project object model, which treats an entire project as an object, similar to Java's OOP (object-oriented). It is possible to complete the project by describing the information

's build.

 

Maven has a very important concept called "repository". In the traditional conservative development model, the following situations are common:

We will create many projects at the same time at work, and each project may reference some common jar packages. One way is to copy a copy of these dependent jar packages (or dll files) in each project, which is obviously not good. , the same file is saved in multiple copies on the hard disk, which takes up too much space.

Moreover, the versions of these dependent jar packages (or dll files) are not easy to manage (for example, if a public jar package is upgraded from 1.0 to 2.0, if all projects referencing this jar package need to be updated, they must be updated one by one. Revise).

The maven warehouse solves these problems very well. It creates a local warehouse on each machine, and manages the jar packages that all the maven projects on the machine depend on, and these jar packages are uniquely identified by "coordinates" (It can be understood as the identifier that "uniquely identifies the file name and version number of a jar package"), so that all maven projects do not need to copy the jar package to the lib directory as before, and the whole maven project looks very refreshing.

 

2. Install maven and configure environment variables

First download the latest version from the official website http://maven.apache.org/download.cgi, after downloading, unzip the compressed file to a certain path, such as: E:\apache-maven-3.3.9

Then configure the environment variables, which is similar to configuring the environment variables of jdk: create a new variable of MAVEN_HOME:E:\apache-maven-3.3.9, and then add ;%MAVEN_HOME%/bin to Path.

Run the command mvn -v in the dos window. If the maven installation version information appears, it means that the maven installation is successful~ Note: mvn is the core command of maven.

In use

 

3. Warehouse and settings.xml configuration file

The settings.xml configuration file is used to determine various configurations of maven at runtime. This includes the location of the local repository, the remote repository server, and authentication information.

settings.xml exists in two places:

One is the user installation directory: %MAVEN_HOME%/conf/settings.xml -- user configuration,

The second is the user's directory such as: C:/Users/username/.m2/settings.xml -- global configuration

User configuration takes precedence over global configuration, and content will be merged when both exist.

The following is a typical settings.xml configuration file:

<settings>
	<!-- The configuration of the local repository, the default is C:/Users/username/.m2/repository -->
    <localRepository>E:\mvn-repository</localRepository>
	<!-- Whether you need to interact with the user to get input -->
    <interactiveMode>true</interactiveMode>
	<!-- Do you need to run in offline mode -->
    <offline>false</offline>
	
	<!--Mirror list of remote repository-->
    <mirrors>  
		<mirror>  
		<!--Mirror ID -->
		  <id>xx-repository</id>  
		  <!-- image name-->
		  <name>test Repository Manager</name>  
		  <!--The URL of this mirror. The build system will use this URL in preference to the default server URL. -->  
		  <url>http://xx.xx.xx.xx:10000/nexus/content/groups/test</url>  
		  <!-- mirrored server ID, use * to represent all -->
		  <mirrorOf>*</mirrorOf>  
		</mirror>  
    </mirrors>
	<!-- Some settings on the server-->
	<servers>
		<server>
			<!--server的id -->
            <id>xxx</id>
			<!--Authentication username. The authentication user name and authentication password indicate the login name and password required for server authentication. -->  
            <username>xxx</username>
			 <!--Authentication password. The authentication user name and authentication password indicate the login name and password required for server authentication. -->
            <password>xxxx</password>
        </server>
		<server>
            <id>xxx</id>
            <username>xxx</username>
            <password>xxxx</password>
        </server>
    </servers>
	 <!--Adjust a list of build configurations based on environment parameters. -->
    <profiles>
		 <!--Configuration of components adjusted according to environment parameters-->  
        <profile>
			<!-- The unique identifier of the configuration -->
            <id>xxx</id>
			<!--Automatically trigger the conditional logic of the profile. Activation is the key to opening the profile. -->
            <activation>
				<!-- The identity of whether the profile is activated by default -->
                <activeByDefault>true</activeByDefault>
				<!-- jdk version-->
                <jdk>1.7</jdk>
            </activation>
			<!--Remote repository list, which is a set of remote projects used by Maven to populate the local repository of the build system. -->  
            <repositories>
                <repository>
				<!-- The unique identifier of the remote repository -->
				  <id>center</id>
				  <!--Remote warehouse name-->
				  <name>center</name>
				  <!--How to handle the download of the release version in the remote repository-->
				  <releases>
					<!--true or false indicates whether the repository is enabled for downloading a certain type of component (release version, snapshot version). -->  
					<enabled>true</enabled>
					<!-- Specifies how often the local repository is updated, i.e. how often it is synchronized with the remote repository. -->
					<updatePolicy>always</updatePolicy><!-- always (always), daily (default, daily), interval: X (where X is the interval in minutes), or never (never). -->
					 <!--What to do when Maven fails to verify the artifact verification file:-->
					<checksumPolicy>warn</checksumPolicy><!--ignore (ignore), fail (fail), or warn (warn). -->
				  </releases>
				  <!--How to handle the download of snapshot versions in remote repositories. With the two sets of configurations releases and snapshots, POM can take a different strategy for each type of artifact in each individual repository. -->  
				  <snapshots>
					<enabled>true</enabled>
					<updatePolicy>always</updatePolicy>
					<checksumPolicy>fail</checksumPolicy>
				  </snapshots>
				  <!--Remote warehouse URL-->
				  <url>http://xx.xx.xx.xx:10000/nexus/content/groups/test</url>
				  <!--Repository layout type for positioning and ordering widgets - can be default (default) or legacy (legacy). -->
				  <layout>default</layout>
				</repository>
 	        </repositories>
			<!--List of remote repositories where plugins are found. The warehouse is home to two main components. The first type of component is used as a dependency of other components. This is the majority of the artifact types stored in the central repository. Another type of widget is a plugin. -->  
		    <pluginRepositories>
				<!-- Information about connecting to the remote plugin repository, similar to repository -->
            	<pluginRepository>
                  <id>plugins</id>
                  <name>Plugins</name>
                  <releases>
                    <enabled>true</enabled>
                    <updatePolicy>always</updatePolicy>
                    <checksumPolicy>warn</checksumPolicy>
                  </releases>
                  <snapshots>
                    <enabled>true</enabled>
                    <updatePolicy>always</updatePolicy>
                    <checksumPolicy>fail</checksumPolicy>
                  </snapshots>
                  <url>http://xx.xx.xx.xx:10000/nexus/content/groups/test</url>
                  <layout>default</layout>
                </pluginRepository>
            </pluginRepositories>
	   </profile>	    
	</profiles>
	<!-- List of manually activated profiles -->
	<!--Any profile id defined in activeProfile, regardless of environment settings, the corresponding profile will be activated. -->  
    <!--If there is no matching profile, nothing happens. For example, if env-test is an activeProfile, the profile corresponding to the id in pom.xml (or profile.xml) will be activated. -->
    <activeProfiles>
        <activeProfile>test</activeProfile>
    </activeProfiles>
</settings>

 

A note about the configuration file has been given.

Note: When importing a project from a remote location or creating a project for the first time, the jar package information will be downloaded from the specified mirror to the local warehouse. In the future, the jar package that the local project depends on will be located in the local warehouse.

 

4. Create a maven project

1) First switch to the working directory such as: F:/gitwork

2) Run the command mvn archetype:generate in this directory to create a maven project, but it is recommended to bring multiple parameters at the same time:

 -DgroupId=com.company.appname 组id

-DartifactId=appname project name, maven will create a new directory with this name in the current directory based on this name to build the project

-DinteractiveMode=false Whether the interactive mode has been carried out, if it is false, the project will be created with the default settings

For example: mvn archetype:generate -DgroupId=com.test -DartifactId=maven-hello -DinteractiveMode=false (by default a general java project is created)

和:mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.company.appname -DartifactId=appname(创建web项目)

Of course, in actual development, it is generally imported remotely or created with IDE tools~

3) We import the created maven project into IDE tools such as Eclipse:

General project:



 

The main focus is on the structure of a general project:

src/main/java - where the java code is stored;

src/test/java - where the test code is stored

target - where to store compiled files

pom.xml - a configuration file describing the information of the maven project

web project:



 

The main structure is similar to that of general projects (except that there is no place to store Java code created by default here, you can build your own package), mainly in a few more places:

src/main/resources - where resource files are stored;

webapp - a place to store configuration files such as xml, such as Spring's configuration files.

 

5. Understand the pom.xml configuration file

The main relationships in pom are divided into: inheritance, dependency and aggregation. These three relationships are not independent of each other, they are often used in combination.

 

After creating a maven project, a pom.xml configuration file will be generated in the root directory of the project.

The pom.xml file is the main configuration file for Maven to work. When Maven builds a project, it is based on the pom.xml under the Maven project. The information that our project depends on and some basic information are defined in this file.

For a simplest pom.xml definition, it must contain four elements, modelVersion, groupId, artifactId, and version. Of course, these elements can also be inherited from its parent project.

In Maven, use groupId, artifactId and version to form groupdId:artifactId:version to uniquely identify a project.

 

1) pom dependencies

The most common is the concept related to the warehouse mentioned above. We only need to add a dependency sub-node under the dependencies node to rely on a jar package or project~

<dependency><!-- This is a format that depends on another project. If it depends on a jar package, it must be written separately -->  
      <groupId>cn.itcast.maven</groupId>  
      <artifactId>HelloFriend</artifactId>  
      <version>0.0.1-SNAPSHOT</version>  
      <scope>compile</scope>  
</dependency>

 

Dependency jar package:

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
</dependency>

 

2) Inheritance of pom

As mentioned earlier, pom is a bit similar to oop, and we can understand the entire project as an object. Coincidentally, pom also has inheritance.

Inheritance In order to eliminate duplication, we extract a lot of the same configuration (for example, in maven interdependent projects, different projects have the same jar package configuration, so it is not too many and cumbersome, you need to configure it every time , very troublesome)

 

Therefore, maven provides a parent class maven project (a new parent class project Parent, the purpose of which is to eliminate duplicate content in the configuration file of the subproject) to install all public jars, which can be used as long as they are inherited.

First, configure the dependent public jar package in the pom.xml of the parent project, and then introduce the parent project into each sub-project, which is generally placed on the <dependencies> node. At this time, each sub-project does not need to add the public jar package to the pom.xml. dependencies, just add the respective

The required jar package dependencies can be.

<parent>  
   <groupId>cn.itcast.maven</groupId>  
   <artifactId>Parent</artifactId>  
   <version>0.0.1-SNAPSHOT</version>  
   <relativePath>../Parent/pom.xml</relativePath>  
</parent>

  

But at this time, the parent project is an aggregate project without actual code. The packaging of its pom.xml should be pom.

 

3) Aggregation of pom

In the process of development, we often have the practice of sub-module development. For example, a project has a web module (a module that directly interacts with the UI), and a facade module (an interface module provided to other projects through webservice),

Service modules (functional modules that implement interface modules of other projects), etc. If these are not divided into modules, it will be very messy, but after the modules are divided, the level will be much clearer. Maven provides support for the management of each module (actually a project),

is aggregation.

In the parent project (aggregated object), the modules section of pom.xml is defined as follows:

<groupId>com.web</groupId>
  <artifactId>maven-web</artifactId>
  <packaging>pom</packaging>
  .....
<modules>
  <module>maven-web-facade</module> <!--The value of each module attribute is the artifactId of each module-->
  <module>maven-web-service</module>
.....
 </modules>

 

And each submodule, such as the pom.xml of the facade module:

<parent>
    <groupId>com.myhost.myapp</groupId>
    <artifactId>myapp</artifactId>
    <version>1.0</version>
  </parent>
  <groupId>com.myhost.myapp</groupId>
  <artifactId>myapp-facade</artifactId>
  <version>1.0</version>
  <name>myapp-facade</name>

 

 Similarly, the pom.xml of the service module:

 

<parent>
    <groupId>com.web</groupId>
    <artifactId>maven-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.web</groupId>
  <artifactId>maven-web-service</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>maven-web-service</name>

 

  

 For intuitive feeling, it is recommended to build a working set in eclipse, and put the aggregation and the aggregated project in the same working set. Then select "Working Set" in the inverted triangle of Top Level Elements of Pacakge Exploer in eclispe,

 The display effect is as follows:

 



 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042491&siteId=291194637