Main Content Introduction
- What is Maven
- What is Maven
- Maven installation and configuration
- Maven coordinates
- Maven rely on
- Maven relies on mediation principles
- Maven Life Cycle
- Maven commands
- Maven plugin
- Maven repositories
- The use of the Profile
- Aggregation and inheritance
- Jenkins environment building
What is Maven
Maven is a cross-platform project management tool for project construction, dependency management and project information management on the Java platform.
Maven installation and configuration (this article is for MAC users)
Maven installation depends on JDK. First, you need to ensure that the JDK is successfully installed by entering the following command to verify whether the JDK is successfully installed:
Jason$Java -version Java Version "1.8.0_231" Java(TM) SE Runtime Environment (build 1.8.0_231-b11) Java HotSpot(TM) 64-bit Server VM (Build 25.231-B11, Mixed mode)Copy the code
If the preceding information is displayed, the JDK is successfully installed
2. Download the Maven installation package from maven.apache.org/ to apache-Maven-3.6.3-bin.tar. gz
Tar -zxvf apache-3.6.3-bin.tar. gz -c /usr/local/; tar -zxvf apache-3.6.3-bin.tar. gz -c /usr/local/; // Unzip to the specified directoryCopy the code
3. Add the environment variable vim ~/. Bash_profile add the following:
export M2_HOME=/usr/local/maven
export PATH=$PATH:$M2_HOME/bin
Copy the code
Run the source. bash_profile command for the configuration to take effect
4. Verify that Maven is successfully installed:
Jason - Pro: Apache Maven 3.6.2 ~ Jason $MVN - v (40 f52333136460af0dc0d7232c0dc0bcf0d9e117; 2019-08-27T23:06:16+08:00) Maven Home: /usr/local/ Maven Java version: 1.8.0_231, Vendor: Oracle Corporation, Runtime: / Library/Java/JavaVirtualMachines jdk1.8.0 _231. JDK/Contents/Home/jre Default locale: zh_CN, platform encoding: Utf-8 OS name: "MAC OS X ", version: "10.14.5", ARCH: "x86_64", family:" MAC"Copy the code
The installation is successful
Maven coordinates
Maven coordinates of any one component to define uniqueness, through the groupId, artifactId, version, packaging,
classifier
Let’s start with the definition of a set of coordinates
<dependency> <groupId> <artifactId>junit</artifactId> <version>4.11</version> <packaging>jar</packaging> </dependency>Copy the code
The definition of each coordinate element is explained below:
- GroupId: Defines the actual project that the current Maven project belongs to. It is usually named in reverse one-to-one correspondence to represent an organization or company
For example, groupId is defined as com.tech. Java
- ArtifactId: Name of the actual project
- Version: indicates the version of the current project
- Packaging: Defines how Maven projects are packaged
- Classifier: The subordinate components that help define the output of the component, corresponding to the master component
Maven coordinates the groupId, artifactId, version is a must, packaging is optional (the default is jar), classifier is not directly defined.
Maven rely on
Maven has the following dependencies:
- Compile: The dependency range, which is default if not specified, applies to all phases and is released with the project
- Test: Test dependency scope. This dependency is required both at test time and at run time. A typical example is junit.jar, which does not ship with the project
- Provided: Provides scope of dependencies that are valid for compile and test classpath, but not at runtime. A typical example is servlet-api.jar
- Runtime: Run-time dependency scope, valid for testing and running the classpath, but not for compiling main code a typical example is JDBC drivers
- DependencyManagement (type= POm dependency) – dependencyManagement (type= POm dependency
- System: system dependency scope. Maven does not repositoy any of the local jars, such as the SHORT message JAR
For example, in a project you want to introduce an external SMS message, sms.jar
<dependency> <groupId>sms-jar</groupId> <artifactId> SMs-jar </artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/lib/*. Jar </systemPath>Copy the code
Maven relies on the principle of mediation
We sometimes run into maven JAR conflicts due to passing dependencies. Here are the principles of dependency mediation
- The shortest path principle (Direct dependency > Transitive dependency)
- Claim priority (if the length of dependent paths is equal, use the claim priority principle)
- Exclusion principle (When passing a dependency conflict, you can declare an exclusion in the passing dependency of a JAR that is not needed, which is used to exclude dependencies)
- Version locking principle (Declare which version of jar to use in the configuration file pom.xml, and no other versions will be dependent upon the declaration)
- Optional dependencies, which are declared by the tag to indicate that the JAR only affects the project and that the dependency is not passed
Maven Life Cycle
The Maven life cycle consists of clean,default, and Site.
- The purpose of the clean lifecycle is to clean up projects
- The purpose of the Default life cycle is to build projects
- The site lifecycle is the creation and publication of project sites
Clean Life cycle
- Pre-clean Performs tasks that need to be completed before cleaning
- Clean Cleans up the files generated during the last build
- Post-clean Performs some work that needs to be done after the cleanup
Default Life Cycle
Includes the following phases:
- validate
- initialize
- generate-sources
- process-sources
- generate-resources
- process-resources
- Compile The main source code of the project
- process-classes
- generate-test-sources
- process-test-sources
- generate-test-resource
- process-test-resouces
- test-compile
- process-test-classes
- Test uses the unit testing framework to run tests, and the test code is not packaged or deployed
- prepare-package
- Package takes compiled code and packages it into publishable formats such as JAR,WAR
- pre-integration-test
- integration-test
- post-integration-test
- verify
- Install installs packages into Maven’s local repository for use by other Maven projects locally
- Deploy copies the final package to a remote repository for use by any other development and Maven project
Site Life Cycle
- The pre-site performs some work that needs to be done before the project site can be generated
- Site generates project site documents
- A post-site performs some of the work that needs to be done after the project site is generated
- Site-deploy publishes the generated project site to the server
Maven commands
List all dependencies for the project
mvn dependency:list
Copy the code
Analyze the dependencies needed to compile the main and test code
mvn dependency:analyze
Copy the code
Print dependent tree structure
mvn dependency:tree
Copy the code
Printing depends on the tree structure information is the most complete
mvn dependency:tree -Dverbose
Copy the code
The print information needs to contain the specified JAR
mvn dependency:tree -Dverbose -Dincludes=junit:junit
Copy the code
Print the jar that the information specifies to filter
mvn dependency:tree -Dverbose -Dexcludes=juit:junit
Copy the code
Project packaging skips testing
MVN clean package-dskiptests // Skip unit tests MVN clean package-dmaven.test.skip =trueCopy the code
Force Maven to check for updates
mvn clean install -U;
Copy the code
Multithreaded parallel compilation
mvn clean -Dmaven.compile.fork=true
Copy the code
Multithreaded parallel packaging
mvn clean -Dmaven.package.fork=true
Copy the code
Multithreading installs jars locally in parallel
mvn clean -Dmaven.install.fork=true
Copy the code
Publish jar to private server
mvn deploy mvn deploy -U ; // Update the latest JAR packageCopy the code
Maven Multithreaded Build
mvn -T 4 clean install
Copy the code
mvn -T 1C clean install
Copy the code
Parameter Description:
- -t 4 specifies four threads
- -t 1C Indicates the multiple of CPU threads
Compile the project in Debug mode
mvn clean compile -X
Copy the code
Use Maven to start the Tomcat project
mvn tomcat:run
Copy the code
Maven plugin
Before introducing the Maven plug-in, explain a few concepts
- Phase: Lifecycle is the total task, and phase is a sub-task that is divided into the total task. Phase actually performs goal. If a phase is not bound, Lifecycle can contain any phases. Phases can be executed sequentially. A phase can be bound to many goals, at least one
- Goal: This is the smallest unit to perform a task. A Goal is independent and can be bound to multiple phases or none at all. If a goal is not bound to either lifecycle it can still be called directly and not called by Lifecycle
- Mojo: A Mojo is an implementation class that does something. Mojo is an implementation class that is derived from AbstractMojo
Maven plugin:
- maven.apache.org/plugins/
- www.mojohaus.org/plugins.htm…
How do you write a plug-in
Background: Write a plug-in that counts the number of files and lines of code for a specific project
1. Introduce dependencies
< the dependency > < groupId > org, apache maven < / groupId > < artifactId > maven plugin - API < / artifactId > < version > 3.5.0 < / version > </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> < artifactId > maven plugin - annotations < / artifactId > < version > 3.5 < / version > < / dependency >Copy the code
In pom. XML, set the packaging type to Maven-plugin
<packaging>maven-plugin</packaging>
Copy the code
2. Define a plug-in class that inherits AbstractMojo
@Mojo(name = "autoScanCount", requiresProject = false, DefaultPhase = lifecyclePhase. PACKAGE) public class extends AbstractMojo {defaultPhase = lifecyclePhase. PACKAGE) public class AutoScanCode extends AbstractMojo List<String> fileList = new ArrayList<>(); @Parameter(name = "currentBaseDir", defaultValue = "/workspace") private String currentBaseDir; @Parameter(name = "suffix", defaultValue = ".java") private String suffix; Private int lines = 0; @Override public void execute() throws MojoExecutionException, MojoFailureException { autoScanDir(currentBaseDir); System.out.println(" + filelist.size ()); System.out.println(" automatic scan code plug-in total number of lines :" + lines); } private void autoScanDir(String baseDir) {File files = new File(baseDir); private void autoScanDir(String baseDir) {File files = new File(baseDir); For (File File: files.listfiles ()) {if (file.isdirectory ()) {autoScanDir(file.getabsolutePath ()); } else { if (file.getName().endsWith(suffix)) { fileList.add(file.getName()); lines += countLine(file); }}}} // Count count private int countLine(File File) {int codeLine = 0; try { BufferedReader reader = new BufferedReader(new FileReader(file)); while (reader.ready()) { reader.readLine(); codeLine++; } } catch (Exception e) { e.printStackTrace(); } return codeLine; }}Copy the code
3. Install the project locally to the local repository and introduce project dependencies to other projects
<dependencies> <dependency> <groupId>com.java.tech</groupId> <artifactId>auto-scan-code</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> < the groupId > com. Java. Tech < / groupId > < artifactId > auto scan - code < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < configuration > Java </suffix> </suffix> </configuration> <executions> <execution> <phase>clean</phase> <goals> <goal>autoScanCount</goal> </goals> </execution> </executions> </plugin> </plugins> </build>Copy the code
4. Run the MVN clean command in the current project to take effect. For more code, see project Demo
Maven repositories
Local repository
A local repository is a directory for storing dependent files. By default, the local repository is located in the. M2 /repository directory of the user directory
Vim ~/.m2/repository
<localRepository>/usr/local/repo</localRepository>
Copy the code
~/.m2/setting.xml-> Maven /conf/setting.xml
- M2 /setting. XML, then conf/setting.xml
- Repository order: Local repository -> Private server -> Maven central repository
Remote Warehouse (Nexus)
Remote repositories are mainly used to solve the jar dependency problem, and many companies choose to build their own private servers for easy downloading of components due to slow Internet downloading
The default is to search for components in the local repository, download them to the local repository if they are not available, or download them from maven’s central repository if they are not already available.
There are many warehouse management software on the market
- Sonatype Nexus
- Jarvana
- MVNrepository
Here we highlight the advantages of using Nexus Private server
- Save bandwidth
- Speeding up Maven builds
- Deploying third-party Artifacts
- Reduce the pressure on the central warehouse
Nexus Warehouse type:
- Group (Warehouse Group)
- Hosted: Manages the local repository
- The proxy (agent)
- Virtual (virtual)
Use of warehouse
- Codehaus Snapshots: Snapshots that manage the Codehaus Snapshot repository
- Apache Snapshots: Describes Snapshots in the Apache Snapshot repository
- Central: This repository is Maven’s Central repository for downloading and caching release artifacts from the Central repository
- Release: Host-type repository with a policy of Release used to deploy Release artifacts within an organization’s internal structure
- Snapshots: Host-type repositories with Snapshots as their policies. Snapshots are Snapshots that are used to call Snapshots of the internal structure of an organization
Nexus installation and startup
Download the Nexus. 2. Decompress the Nexus file to a specified directory
Tar -zxvf nexus-public-release-3.21.0-05.tar.gz -c /usr/local/nexusCopy the code
3. In the/usr/local/nexus/bin/nexus documents include:
export RUN_AS_USER=root
Copy the code
4. Run./nexus start To start the Nexus
Sonatype-work files in Nexus
- Conf: stores configuration files such as the log private service permission
- Indexer: Stores index files. The jar displayed on the private server page is searched for in the storage through the index
- Storage :jar package stores files
- Logs: Stores log files
The use of the Profile
Profiles address the problem that projects may be configured differently in different environments, such as development, test, and production environments, such as data source configuration, log file configuration, and some basic configurations during software execution
Changing the configuration file each time you deploy the software to a different environment can be error-prone and labor-intensive.
It is typically configured in pom.xml
<profiles> <profile> <! -- profileId for unique --> <id>dev</id> <properties> <env>dev</env> </properties> <activation> <! -- Activate the profile node by default --> <activeByDefault>true</activeByDefault> </activation> <build> <resources> <resource> <directory>src/main/resources/dev</directory> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </profile> <profile> <! Qa </id> <properties> <env> QA </env> </properties> <build> <resources> <resource> <directory>src/main/resources/qa</directory> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </profile> <profile> <! Prod </id> <properties> </env> </properties> <build> <resources> <resource> <directory>src/main/resources/prod</directory> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </profile> </profiles>Copy the code
Environment packaging is specified using maven command parameters
Maven is packaged using the -p parameter followed by the profile ID
mvn clean install -Pdev
Copy the code
Aggregation and inheritance
Maven’s aggregation features allow the modules of a project to be built together, while Maven’s inheritance features help extract the same configuration of dependencies and plug-ins from each module
While simplifying POM, it also promotes consistency across module configurations
Aggregation is the aggregation of various modules of a project, such as this project is an aggregation
<modules>
<module>java8</module>
<module>design-pattern</module>
<module>mybatis</module>
<module>maven</module>
</modules>
Copy the code
Inheritance is the definition of some generic JARS in the parent POM.xml
DependencyManagement is a dependency
- DependencyManagement is a predefined declaration that only appears in the parent POM. The version number is the same. The child POM is referenced on demand
- Dependency references only jar dependent ones
distributionManagement
- Used to specify the location of maven distributions
- Maven treats release builds differently from Snapshot builds
- The release version is stable and cannot be overwritten
- Snapshot is the version of the development process. Real-time but unstable versions can be overwritten
Jenkins environment building
Jenkins is collectively known as the continuous integration platform (CI).
IO /zh/download…
# OS Specific support. $var must be set to either true or false:
JENKINS_HOME=/data/jenkins
Copy the code
3. Edit the profile file vim /etc/profile to add JENKINS_HOME to the environment variable
export JENKINS_HOME=/data/jenkins
Copy the code
Run source /etc/profile for the configuration to take effect
4. In the/usr/local/tomcat/bin/catalina. Sh below with the following contents:
CATALINA_OPTS="$CATALINA_OPTS -server -Djava.awt.headless=true -Xms1g -Xmx1g -Xss256k -XX:NewSize=600m -XX:MaxNewSize=600m -XX:SurvivorRatio=8 -XX:+UseParNewGC -XX:ParallelGCThreads=4 -XX:MaxTenuringThreshold=15 -XX:+UseConcMarkSweepGC -XX:+DisableExplicitGC -XX:+UseCMSInitiatingOccupancyOnly -XX:+ScavengeBeforeFullGC -XX:+UseCMSCompactAtFullCollection -XX:+CMSParallelRemarkEnabled -XX:CMSFullGCsBeforeCompaction=9 -XX:CMSInitiatingOccupancyFraction=80 -XX:+CMSClassUnloadingEnabled -XX:SoftRefLRUPolicyMSPerMB=0 -XX:-ReduceInitialCardMarks -XX:+CMSPermGenSweepingEnabled -XX:CMSInitiatingPermOccupancyFraction=80 -XX:+ExplicitGCInvokesConcurrent -Djava.nio.channels.spi.SelectorProvider=sun.nio.ch.EPollSelectorProvider -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -DJENKINS_HOME=/data/jenkins -Dhudson.model.DirectoryBrowserSupport.CSP="
CATALINA_OPTS="$CATALINA_OPTS -Duser.timezone=Asia/Shanghai -Dclient.encoding.override=UTF-8 -Dfile.encoding=UTF-8"
Copy the code
5. Put Jenkins. War into the Tomcat directory webapps and run Tomcat
sh /usr/local/tomcat/bin/startup.sh
Copy the code
At this point Jenkins has started and is accessed by typing http://localhost:8080 in a browser
Copy the code