Maven

Xu Yuxi 2021-01-22 18:14:29
maven


Maven

primary coverage

Maven An introduction to the

brief introduction

​ Maven【[ˈmevən]】 This word can be translated into " Experts ",“ adept ”. As Apache One of the most successful open source projects in the organization ,Maven Mainly based on java Project construction of the platform , Dependency management and project information management .

​ Whether it's a small open source class library project , Or large enterprise applications ; Whether it's traditional waterfall development , Still popular agile development ,Maven They can show their skills .

The project build

​ Whether you realize it or not , structure (build) It's what every programmer does every day . Come to the company in the morning , The first thing we do is check out the latest code from the source library , And then do unit testing , If the test fails , Will find relevant colleagues to debug , Fix the error code . Then go back to your work , Write your own unit test and product code .

​ To sum it up carefully , We will find that , Besides writing source code , We spend a lot of time every day compiling , Run unit tests , Generating documentation , Packaging and deployment and other tedious and trivial work , This is building . If we do it by hand now , The cost is too high , So someone used software to make this series of work completely automated , So that the software can be built like a fully automated pipeline , Just a simple command , All the tedious steps can be done automatically , It's going to get the final result soon .

Project building tools

Ant structure

​ The first build tool , be based on IDE, Probably 2000 There are some in the year , It was the most popular java Building tools , But its XML Script format makes XML The documents are very large . Especially good at process control during engineering construction

Maven【JAVA】

​ Project object model , Manage the construction of a project through its descriptive information , Software project management tools for reporting and documentation . It fills in Ant shortcoming ,Maven For the first time, it supports downloading from the Internet , Still used xml As a configuration file format .Maven Focus on dependency management , Use Java To write .

**Gradle** 

​ It belongs to the advantages of combining the above two , It inherited Ant Flexible and Maven Life cycle management of , It ended up being google As a result of Android Management tools for the Emperor . The biggest difference is that it doesn't have to XML As a configuration file format , Adopted DSL Format , Make the script more concise .

​ Currently on the market Ant Relatively old , So it is generally used by some traditional software companies ,Maven Use Java To write , It's a building tool that most Internet companies will use today , Chinese documents are also quite complete , gradle Yes, it is groovy To write , At present, some new building tools are used by some start-up Internet companies , There will be a lot of space to use in the future .

Maven Four characteristics of

Dependency management system

​ Maven by Java The world has introduced a new dependency management system jar Package management jar When upgrading, you can modify the configuration file . stay Java In the world , It can be used groupId、artifactId、version Composed of Coordination( coordinate ) Uniquely identifies a dependency .

​ Anything based on Maven The built project itself must also define these three attributes , The generated package can be Jar package , It can also be war Packages or jar package . A typical dependency reference is shown below :

<dependency>
<groupId>javax.servlet</groupId> com.baidu
<artifactId>javax.servlet-api</artifactId> ueditor echarts
<version>3.1.0</version>
</dependency> 

Understanding of coordinate properties

​ Maven Coordinates introduce order to the various components , Any component must clearly define its own coordinates .

groupId

​ Define the current Maven The actual project to which the project belongs - Corporate name .(jar The path of the warehouse where the package is located ) because Maven The concept of module in , So a real project is often divided into many modules . such as spring It's a real project , Their corresponding Maven There will be a lot of modules , Such as spring-core,spring-webmvc etc. .

artifactId

​ This element defines one of the actual projects Maven modular - Project name , The recommended practice is to use the actual project name as artifactId The prefix of . such as : spring-bean、 spring-webmvc etc. .

version

​ This element defines Maven The current version of the project .

Multi module building

​ During project review dao service controller Layer separation is a common way to decompose a project into multiple modules .

​ stay Maven You need to define a parent POM As a group module The aggregation of POM. In the POM Can be used in Tag to define a set of submodules .parent POM There won't be any actual build output . and parent POM Medium build Configuration and dependency configuration are automatically inherited to children module.

Consistent project structure

​ Ant The times created Java Project directory is more casual , And then through Ant Configuration specifies which belong to source, Those belong to testSource etc. . and Maven The idea at the beginning of the design was Conversion over configuration( Convention over configuration ). It developed a set of project directory structure as a standard Java Project structure , Solve the difference ide File directory inconsistency caused by this problem .

Consistent build model and plug-in mechanism

<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.25</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<contextPath>/test</contextPath>
</configuration>
</plugin> 

Maven Installation configuration and directory structure of

Maven Installation configuration

Check JDK Version of

​ JDK edition 1.7 And above

download Maven

​ Download address :http://maven.apache.org/downl...

To configure Maven environment variable

​ After decompression Maven The root directory of is configured into the system environment variable MAVEN_HOME, take bin Directory configuration to path variable .

​ notes :maven After decompression, the directory should not contain Chinese and spaces

Check Maven Is the installation successful

​ open dos window , perform mvn

know Maven Directory structure

Mission : Manually create a Maven project , And compile and run successfully !

Create a folder as the root of the project

Create a pom.xml file , The contents are as follows

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxxx</groupId>
<artifactId>maven01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>maven01</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project> 

Ps: Label definition explains

 The first child element in the root directory ModelVersion Specify the current Pom The version of the model , about Maven3 Come on , It can only be 4.0.0 . Specifies the current Maven Version number of the model , about Maven2 and Maven3 Come on , It can only be 4.0.0
groupId Defines which group the project belongs to , This group is often associated with the organization and company where the project is located .
such as : com.xxxx
artifactId Defines the current Maven The project is unique in the group ID.
Version X.X.X- Milepost
such as :1.0.0-SNAPSHOT
first X The big version There's a big change
the second X Small version Repair bug, Add function
Third X to update
Milestone version :
SNAPSHOT ( snapshot , Development Edition )
alpha( Internal test )
beta( Public testing )
Release | RC( Release )
GA( Normal version )
Use name The tag declares a more user-friendly project name , Although not necessary , But it's still recommended for everyone Pom Statement name, To facilitate the exchange of information . 

Write the main function

package com.xxxx.demo;
public class Hello{
public static void main(String[] args) {
System.out.println("hello maven");
}
} 

cmd Compile and run

​ cmd below , Go to the root of the project

​ 1. compile java file

​ mvn compile

​ 2. perform main Method

​ mvn exec:java -Dexec.mainClass=“com.xxxx.demo.Hello”


notes : The first download will be slow , To be modified maven After decompression conf In the catalog settings.xml.

1.1. The default location of the warehouse is modified
open maven Catalog -> conf -> settings.xml
Add warehouse location configuration
<localRepository>F:/m2/repository</localRepository>
notes : The warehouse location is changed to the specified directory of your own machine ,"/" Don't write backwards
1.2. Change Ali image , Speed up dependent downloads
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror> 

If the compilation fails , Possible problems

1. Not with administrator rights dos command
2. JDK There is a problem with the environment configuration , reinstall JDK
3. When coding , There is no package name set in the class ( If no package name is added to the class at compile time , No need to add package name when executing ) 

Maven command

​ As a development tool maven, It gives us a very rich command , understand maven Command line operations and skilled use of common maven Orders are still necessary , Even if, for example IDEA And other tools have provided me with graphical interface tools , But the bottom layer still depends on maven Command driven .

Maven The command format of is as follows :

mvn [plugin-name]:[goal-name] 

The meaning of the command is : perform plugin-name The plug-in goal-name The goal is

Common commands

command

describe

mvn –version

Display version information

mvn clean

Clean up the temporary documents of project production , It's usually under the module target Catalog

mvn compile

Compiled source code , General compiler module under the src/main/java Catalog

mvn package

Project packaging tools , It will be under the module target Directory generation jar or war Wait for the documents

mvn test

The test command , Or execution src/test/java/ Next junit Test cases for .

mvn install

Will be packed jar/war Copy files to your local warehouse , For other modules

mvn deploy

Publish packaged files to remote reference , Provide other people to download and rely on

mvn site

A website that generates project related information

mvn eclipse:eclipse

Turn the project into Eclipse project

mvn dependency:tree

Print out the entire dependency tree of the project

mvn archetype:generate

establish Maven Ordinary java project

mvn tomcat7:run

stay tomcat Running in the container web application

mvn jetty:run

call Jetty The plug-in Run Target at Jetty Servlet Start in container web application

 Be careful : function maven When ordered , First of all, we need to locate maven Project directory , That's the project pom.xml Directory of files . otherwise , The directory of the project must be specified by a parameter . 

Command parameter

​ The above list is just a more general command , In fact, many commands can carry parameters to perform more precise tasks .

-D Pass in property parameter

for example :
mvn package -Dmaven.test.skip=true

​ With -D start , take maven.test.skip The value of the set true, Just tell maven Skip unit testing when packaging . Empathy ,mvn deploy-Dmaven.test.skip=true Represents the deployment project and skips unit tests .

-P Use specified Profile To configure

​ For example, project development needs to have multiple environments , Usually for development , test , Advance , formal 4 An environment , stay pom.xml The configuration in :

<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>qa</id>
<properties>
<env>qa</env>
</properties>
</profile>
<profile>
<id>pre</id>
<properties>
<env>pre</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
......
<build>
<filters>
<filter>config/${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
......
</build> 

profiles Defines the variables of each environment id,filters The address of the variable configuration file is defined in , The environment variable in the address is above profile The value defined in ,resources Define which directory files will be replaced by the variables defined in the configuration file .

​ adopt maven It can be deployed in different environments , for example :

mvn package -Pdev -Dmaven.test.skip=true

​ Means to package the local environment , And skip unit testing

IDEA Editor integration Maven Environmental Science

Set up Maven edition

choice “File” —> “Other Settings” —> “Settings for New Projects…” —> Search for “Maven”

Choose download good maven edition ( Select the directory to bin The next level of a directory )

Set up settings.xml file

Once you set it up , choice “Apply” perhaps “OK”

Maven Project creation

establish Java project

New projects

  1. choice “File” —> “New” —> “Project”
  2. choice "Maven", Set up JDK edition , choice maven Template for the project
  3. Set up the GroupId and ArtifactId
  4. Check Maven Environmental Science , choice “Next”
  5. Check the project name and workspace , choice “Finish”
  6. Wait for the project to be created , Download resources , After creation, the directory structure is as follows

    notes : The pop-up box in the lower right corner of , choice “Enable Auto-Import”(Maven Start auto import )

Compile the project

  1. Click on the "Add Configurations ", open “Run/Debug Configurations” window [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-h6mly2QJ-1611216217928)(/maven_14.png)]
  2. Click on the top left “+” Number , choice “Maven”
  3. Set the command to compile the project
  4. Execute compile command , The two icons represent " Common mode " and " Debug mode "[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-pK7UAPBf-1611216217931)(/maven_17.png)]
  5. Compile successfully

establish Web project

Create project

  1. establish Web Project and creation Java The project steps are basically the same , The difference is in choosing Maven Templates (web Project selection webapp), Pictured :[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-pg2cKfLA-1611216217932)(/maven_19.png)]

    notes : Other steps are to create common Java The project is the same .

Start project

modify JDK Version of
<!-- JDN The version of is modified to 1.8 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> 
Set the version of the unit test
<!-- junit The version of is modified to 4.12 -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies> 
Delete pluginManagement label
<!-- Delete the label and the contents of the tag -->
<pluginManagement>
...
</pluginManagement> 
add to web Deployed plug-ins

​ stay build Add... To the tag plugins label

  1. Jetty plug-in unit

    <!-- Set in the plugins In the label -->
    <plugin>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>maven-jetty-plugin</artifactId>
    <version>6.1.25</version>
    <configuration>
    <!-- Thermal deployment , Every time 10 One second scan -->
    <scanIntervalSeconds>10</scanIntervalSeconds>
    <!-- You can specify the site name of the current project -->
    <contextPath>/test</contextPath>
    <connectors>
    <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
    <port>9090</port> <!-- Set the starting port number -->
    </connector>
    </connectors>
    </configuration>
    </plugin> 
  2. Tomcat plug-in unit

    <!-- Set in the plugins In the label -->
    <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.1</version>
    <configuration>
    <port>8081</port> <!-- Start port Default :8080 -->
    <path>/test</path> <!-- Project site name , That is, the external access path -->
    <uriEncoding>UTF-8</uriEncoding> <!-- Character set encoding Default :ISO-8859-1 -->
    <server>tomcat7</server> <!-- Server name -->
    </configuration>
    </plugin> 
Start project
  1. Click on the "Add Configurations ", open “Run/Debug Configurations” window [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-LP8n6wzr-1611216217934)(/maven_14.png)]
  2. Click on the top left “+” Number , choice “Maven”

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dpsJjRd3-1611216217935)(/maven_15.png)]

  3. Jetty The plug-in configuration

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-lsZh1LrI-1611216217935)(/maven_20.png)]

    You can also enter the command to specify the port to start

    jetty:run -Djetty.port=9090 # You need to configure the plug-in port Remove the label 
  4. Tomcat The plug-in configuration

Maven The basic concept of warehouse

​ When the first run Maven When ordered , You need Internet link , Because it needs to download some files from the Internet . So where does it come from ? It's from Maven The default remote library downloads . This remote warehouse has Maven Core plug-ins and downloadable jar file .

​ about Maven Come on , There are only two types of warehouses : Local warehouse and remote warehouse .

​ When Maven When looking for components from coordinates , It first looks at the local warehouse , If a local warehouse exists , Direct use ; If not locally ,Maven Will go to the remote warehouse to find , After finding the required artifacts , Download it to the local warehouse and use it again . If neither the local warehouse nor the remote warehouse has ,Maven You're going to report a mistake .

​ There are three types of remote warehouses : The central warehouse , Private clothes , Other public libraries .

​ The central warehouse is configured by default ,Maven download jar Bag place .

​ Private server is another special remote warehouse , To save bandwidth and time , A private warehouse server should be set up in the LAN , Proxy all external remote warehouses . Internal projects can also be deployed to private servers for other projects .

​ Generally speaking , stay Maven Under project directory , There is no such thing as lib/ This is used to store the directory of dependent files . When Maven During compilation or testing , If you need to use dependency files , It always uses the dependency files of the local repository based on coordinates .

​ By default , Each user has a path named... In their own user directory .m2/repository/ The warehouse directory of . occasionally , For some reason ( such as c Not enough disk space ), Need to modify local warehouse directory address .

​ For the modification of warehouse Path , Can pass maven The configuration file conf Under the table of contents settings.xml To specify the warehouse Path

<!-- Set to the specified directory , Do not reverse the slant bar of the path -->
<settings>
<localRepository>D:/m2/repository</localRepository>
</settings> 

The central warehouse

​ Because the original local warehouse is empty ,maven You must know at least one available remote warehouse , To perform maven Download to the required component at command time . The central warehouse is such a default remote warehouse .

​ maven-model-builder-3.3.9.jar maven automatic jar Contains one Super POM. Defines the location of the default central warehouse .

The central warehouse contains 2000 Multiple open source projects , Receive every day 1 More than 100 million visits .

Private clothes

​ Private server is a special remote warehouse , It is a warehouse service built in LAN , Remote warehouse of private agent Wan , For maven The user to use . When maven When you need to download components , It goes to private servers to find , If there is no private server , Download from an external remote repository , And put it on the private service , Again maven Provide .

​ Besides , Some components that can't be downloaded from the external warehouse can also be uploaded from the local to the private server to be used by others in the LAN

Project configuration mode pom.xml To configure

<repositories>
<repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>public</id>
<name>Public Repositories</name>
<url>http://192.168.0.96:8081/content/groups/public/</url>
</repository>
<repository>
<id>getui-nexus</id> <url>http://mvn.gt.igexin.com/nexus/content/repositories/releases/</url>
</repository>
</repositories> 

Private service should be established inside the company :

  • Save your own bandwidth
  • Speed up maven structure
  • Deploy third-party controls
  • Improve stability
  • Reduce the load of central warehouse

Other public libraries

Common alicloud warehouse configuration

<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror> 

Maven Build a multi module project in the environment

​ Use maven The features of multi module building provided are completed maven Project management and construction of multiple modules in the environment .

 Here we take four modules as examples to build a project , In order to achieve the original intention of being easy to understand
modular maven_parent —– Base module , It's often said parent (pom)
modular maven_dao —– The database access layer , for example jdbc operation (jar)
modular maven_service —– The business logic layer of the project (jar)
modular maven_controller —– Used to receive requests , The response data (war) 

establish maven_parent project

  1. choice File —> Settings —> Project[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-AgWNlYBc-1611216217945)(/maven_37.png)]
  2. Set up GroupId and ArtifactId[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-2lbD4fyx-1611216217947)(/maven_38.png)]
  3. Set project name and workspace [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-gG12H7Tl-1611216217948)(/maven_39.png)]

establish maven_dao modular

  1. Select project maven_parent, The right choice New , choice Module[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-RF15CmXp-1611216217949)(/maven_40.png)]
  2. choice Maven Template for the project ( Ordinary Java project )[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-wHr83MYE-1611216217950)(/maven_41.png)]
  3. Set sub module's ArtifactId[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-uqtjfuCL-1611216217951)(/maven_42.png)]
  4. Set up Maven Configuration of [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ALsEjl0y-1611216217952)(/maven_43.png)]
  5. Set the name and storage location of the sub module [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-xIzstiS8-1611216217953)(/maven_44.png)]

establish maven_service modular

​ establish maven_service Module steps and maven_dao Modules are consistent .

build maven_controller modular

​ establish maven_service Module steps and maven_dao The modules are basically the same , Just select the first step Maven The template is set to web The project is just .( Template type :maven-archetype-webapp)

​ After all modules are created , The effect is as follows :[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-XqSBLIsk-1611216217957)(/maven_45.png)]

Modify the configuration of the module

  • Set up JDK edition
  • unit testing JUnit edition
  • Remove redundant configuration

Set up dependencies between modules

maven_dao

  1. New package

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-HfmIK3DK-1611216217959)(/maven_46.png)]

  2. Create... In the package UserDao class

    Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-3DiXLKJU-1611216217961)(/maven_47.png)

  3. Add methods to the class

    package com.xxxx.dao;
    public class UserDao {
    public static void testDao() {
    System.out.println("UserDao Test...");
    }
    } 

maven_service

  1. add to maven_dao Dependence

    <!-- Join in maven_dao Module dependency -->
    <dependency>
    <groupId>com.xxxx</groupId>
    <artifactId>maven_dao</artifactId>
    <version>1.0-SNAPSHOT</version>
    </dependency> 
  2. Add... To the project UserService class , And add methods

    package com.xxxx.service;
    import com.xxxx.dao.UserDao;
    public class UserService {
    public static void testService() {
    System.out.println("UserService Test...");
    // call UserDao Methods
    UserDao.testDao();
    }
    } 

maven_controller

  1. add to maven_service Module dependency

    <!-- Join in maven_service Module dependency -->
    <dependency>
    <groupId>com.xxxx</groupId>
    <artifactId>maven_service</artifactId>
    <version>1.0-SNAPSHOT</version>
    </dependency> 
  2. add to Servlet Dependence

    <!-- Servlet Dependence -->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
    </dependency> 
  3. newly build Java class , Inherit HttpServlet class , And rewrite service Method

    package com.xxxx.controller;
    import com.xxxx.service.UserService;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    @WebServlet("/user")
    public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("UserServlet Test...");
    // call UserService Layer method
    UserService.testService();
    }
    } 
  4. add to Tomcat plug-in unit

    <!-- Add the plug-in -->
    <plugins>
    <!-- tomcat7 plug-in unit -->
    <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.1</version>
    <configuration>
    <!-- <port>8080</port> -->
    <path>/web</path>
    <uriEncoding>UTF-8</uriEncoding>
    <server>tomcat7</server>
    </configuration>
    </plugin>
    </plugins> 
  5. Start project
  6. Visit the project

    Access address :http://localhost:8080/web/user

  7. If startup fails , Please put the parent project first install

    notes : If the parent project install Failure , Then all the sub modules will be install After success , Again install Parent project .

Maven The packaging operation of

​ For enterprise projects , Whether it's local testing , Or test environment, test and final project launch , It will involve the packaging operation of the project . Package projects for each environment , The corresponding projects need different configuration resources , There are many ways to implement packaging , Can pass ant, Or by idea The self-contained packing function realizes the project packing , But when the project is large and requires a lot of external configuration , At this point, the packaged configuration will be extremely complex , about maven project , We can use it pom.xml Configuration to realize the environment selection when packaging , Compared with other forms of packaging tools , adopt maven Just through simple configuration , You can easily complete the whole package of projects in different environments .

​ Like the following project , The configuration files required by different environments are configured in the project , At this time, you need to complete the packaging operation in different environments , At this point, by modifying pom.xml as follows :

Create the corresponding directory structure

​ Use idea Create project , The directory structure may be missing , You need to manually add the corresponding directory .

  1. add to Java Source folder

    Select the project's main Folder , The right choice New, choice Directory

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-XptBbPp7-1611216217967)(/maven_27.png)]

    Enter folder name “Java”, Pictured :

    Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-IK9n4cuZ-1611216217967)(/maven_29.png)

    choice java Catalog , The right choice Mark Directory as, choice Sources Root. Mark the folder as the source folder .

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-HOtLtYHU-1611216217970)(/maven_31.png)]

  2. Add resource folder

    The steps are as follows , Create folder , Name it resources, And marked as Resources Root[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-IRbmD5lP-1611216217972)(/maven_32.png)]

  3. Add the corresponding folder Directory , And add the corresponding configuration files in different environments .( The local environment 、 Test environment 、 Formal environment )[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-4w7qfQKk-1611216217974)(/maven_33.png)]

add to Profile To configure

<!-- Packaging environment configuration development environment Test environment Formal environment -->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<!-- When no environment is specified , Default packaging dev Environmental Science -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<env>product</env>
</properties>
</profile>
</profiles> 

Set resource file configuration

<!-- For the configuration of project resource file, put it in build in -->
<resources>
<resource>
<directory>src/main/resources/${env}</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.tld</include>
</includes>
<filtering>false</filtering>
</resource>
</resources> 

Perform the packaging operation

open Run/Debug Configuarations window , Enter the corresponding packing command

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nVsOnYe7-1611216217975)(/maven_34.png)]

At this point, it corresponds to the command package

1. `clean compile package -Dmaven.test.skip=true` 

​ Package default environment ( development environment ) And skip maven Test operation

 2. `clean compile package -Ptest -Dmaven.test.skip=true` 

​ Package the test environment and skip maven Test operation

3. `clean compile package -Pproduct -Dmaven.test.skip=true` 

​ Package the production environment and skip maven Test operation

Package successfully

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dGRIVoRH-1611216217976)(/maven_35.png)]

Different project packages , Generally speaking , Ordinary java The project into jar package ,web The project into war package [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-CtswFg7x-1611216217977)(/maven_36.png)]

Maven The basic concept of dependency

Basic configuration of dependencies

​ Root element project Under the dependencies It can contain more than one dependence Elements , To declare multiple dependencies . Each dependency should contain the following elements :

  1. groupId, artifactId, version : The basic coordinates of dependence , For any dependency , The basic coordinates are the most important , Maven You can find the required dependencies according to the coordinates .
  2. Type: The type of dependency , In most cases, you don't need to state . The default value is jar
  3. Scope: Depend on the range (compile,test,provided,runtime,system)

    • compile: Compile dependency range .

      If not specified , The dependency scope will be used by default . Use the... Of this dependency scope Maven rely on , To compile 、 test 、 Run three classpath Are effective .

    • test: Test dependency range .

      Use the... Of this dependency scope Maven rely on , For testing only classpath It works , You will not be able to use such dependencies when compiling the main code or running the project . A typical example is JUnit, It is only needed when compiling test code and running tests .

    • provided: Dependency scope... Has been provided .

      Use the... Of this dependency scope Maven rely on , For compilation and testing classpath It works , But not at run time . A typical example is servlet-api, When compiling and testing a project, you need to rely on , But when running the project , As the container has been provided , There is no need to Maven Introduce... Again and again ( Such as :servlet-api).

    • runtime: Runtime dependency range .

      Use the... Of this dependency scope Maven rely on , For testing and running classpath It works , But not when compiling the main code . A typical example is JDBC Drive implementation , The compilation of the project main code only needs JDK Provided JDBC Interface , The implementation of these interfaces is required only when testing or running a project JDBC drive .

    • system: System dependency range .

      There are three kinds of dependence classpath The relationship between , and provided The range of dependencies is exactly the same . however , Use system Range dependence must be done by systemPath Element explicitly specifies the path of the dependent file . Because such dependence is not through Maven Warehouse parsed , And often with the native system binding , May cause the build to be non portable , Therefore, we should use .

  4. Optional: Whether tag dependency is optional
  5. Exclusions: Used to exclude transitive dependencies .

Depend on the range

​ The first thing you need to know is ,Maven When compiling the main code of the project, you need to use a set of classpath. such as : When compiling the project code, you need to use spring-core, The file is introduced into by dependency classpath in . secondly , Maven Another set will be used when executing the test classpath. Such as :junit.

​ Finally, when you actually run the project , We'll use another set classpath, spring-core It needs to be classpath in , and junit Unwanted .

​ Then dependency scope is used to control dependency and these three kinds of classpath( compile classpath, test classpath, Runtime classpath) The relationship between , Maven There are several dependency ranges :

  • Compile Compile dependency range . If not specified , The dependency scope will be used by default . Use the... Of this dependency scope Maven rely on , To compile , test , It works .
  • Test: Test dependency range . It's only necessary for testing . such as junit
  • Provided: Dependency scope... Has been provided . Use the... Of this dependency scope Maven rely on , Valid for compilation and testing , But not at run time . A typical example is servlet-API, The need to compile and test the project , But when you run the project , As the container has been provided , There is no need to Maven Introduce... Again and again .
  • Runtime: Runtime dependency range . Use the... Of this dependency scope Maven rely on , Effective for testing and running , But it doesn't work when compiling code . A typical example is :jdbc The driver , The compilation of the project main code only needs jdk Provided jdbc Interface , The implementation of these interfaces is required only when testing or running a project jdbc drive .
  • System: System dependency range . Generally not used .

Transitive dependency

​ Transitive dependency mechanism , Let's use something jar You don't have to think about what it depends on . And don't worry about introducing extra dependencies . Maven Will parse the direct dependencies POM, Put the necessary indirect dependence on , Introduced into the current project in the form of transitive dependencies .

​ Be careful : Transitive dependencies can conflict !!

Conflict scenarios :

A-->B--->C (2.0)
A-->E--->C (1.0) 

​ If A There are two differences at the same time version Of C, Conflict !!( Choose to fit at the same time A、B Version of )

<dependencies>
<dependency>
<groupId>A</groupId>
<artifactId>A</artifactId>
<version>xxx</version>
<exclusions>
<exclusion>
<groupId>C</groupId>
<artifactId>C</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>B</groupId>
<artifactId>B</artifactId>
</dependency>
</dependencies> 
版权声明
本文为[Xu Yuxi]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210122180650548I.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云