Maven advanced explanation

Maven advanced

1. Review of Maven basic knowledge

1.1 maven introduction

maven is a project management tool, which is mainly used to manage and build Java projects in the project development stage.

Dependency management: the management of jar packages. Importing maven coordinates is equivalent to importing the jar package in the warehouse into the current project.

Project construction: the whole process of project cleaning, compiling, testing, reporting, packaging and deployment can be completed through a command of maven.

1.2 warehouse type of maven

1. Local warehouse

2. Remote warehouse

① Maven central warehouse (address: http://repo2.maven.org/maven2/ )

② maven private server (the warehouse in the company's LAN needs to be built by yourself)

③ Other public remote warehouses (such as those provided by Apache, address: http://repo.maven.apache.org/maven2/ )

1.3 maven common commands

Clean: clean

Compile: compile

test: test

Package: package

Install: install

1.4 maven coordinate writing specification

1.5 dependency scope of maven

Dependency rangeValid for compiling classpathValid for test classpathValid for runtime classpathexample
compileYYYspring-core
test-Y-Junit
providedYY-servlet-api
runtime-YYJDBC Driver
systemYY-Local, class libraries outside the maven repository

2. maven dependency passing

2.1 what is dependency passing

In maven, dependency is transitive. It is assumed that there are three projects: project A, project B and project C. Assuming that C depends on B and B depends on A, it is not difficult to deduce that project C also depends on A according to the characteristics of Maven project dependence.

As can be seen from the above figure, our web project directly relies on spring webmvc, which relies on spring AOP, spring beans, etc. The final result is that our web projects indirectly rely on spring AOP, spring beans and so on.

2.2 what is dependency conflict

Due to the existence of dependency transfer, spring webmvc relies on sping-beans-4.2.4 and spring AOP relies on spring-beans-5.0.2. However, it is found that sping-beans-4.2.4 is added to the project, and we hope spring-beans-5.0.2 is added to the project. This creates a dependency conflict.

2.3 how to resolve dependency conflicts

1. Use the principle of relying on mediation provided by maven

   Principle of first declaration priority

The principle of "the nearest path first"

2. Exclude dependencies

3. Locked version

2.4 principle of reliance adjustment - the first declaration takes precedence

Define dependency in pom file, and the dependency declared earlier shall prevail. In fact, it is to determine which passed dependency is finally used according to the order of coordinate import.

Conclusion: as can be seen from the above figure, spring beans are passed from both spring AOP and spring webmvc, but because spring AOP is in front, the final spring beans are passed from spring AOP, while the spring beans passed from spring webmvc are ignored.

2.5 exclude dependencies

You can use the exclusions tag to exclude the passed dependencies.

2.6 version locking

The method of directly locking the version is adopted to determine the version that depends on the jar package. After the version is locked, the dependent declaration order or dependent path will not be considered, and the locked version will prevail. This method is often used in enterprise development.

How to use version locking:

Step 1: lock the dependent version in the dependency management tab

Step 2: declare the maven coordinates to be imported in the dependencies tab

① Lock the dependent version in the dependency management tab

② Declare the maven coordinates to be imported in the dependencies tab

3. Construction of SSM project case based on maven

3.1 requirements description

This case builds SSM (Spring + spring MVC + mybatis) project based on maven, and carries out dependency management through Maven coordinates. Finally, it realizes the function of querying commodity information according to id.

3.2 build maven project

1. Database environment construction

① create database ssmtest

② create item table

CREATE TABLE `item` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `price` float default NULL,
  `createtime` datetime default NULL,
  `detail` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2.maven project construction

① Create maven web project

② Configure pom.xml file

③ Realize spring+mybatis integration

Create POJO class

public class Item {
private Integer id;
private String name;
private Float price;
private Date createtime;
private String detail;
//Omit setter and getter
}

Writing of DAO interface in persistence layer

public interface ItemMapper {
       public Item findById(int id);
}

Mapper mapping file authoring

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.ssm.dao.ItemMapper">
<select id="findById" parameterType="int" resultType="item">
         select * from item where id=#{id}</select>
</mapper>

Business layer Service writing

package com.itheima.ssm.service;
import com.itheima.ssm.pojo.Item;
public interface ItemService {
    public Items findById(int id);
} 
@Service
@Transactional
public class ItemServiceImpl implements ItemService {
@Autowired
private ItemMapper itemMapper;
public Item findById(int id) {
return itemMapper.findById(id);
}
}

The spring configuration file is written in applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"      xmlns:context="http://www.springframework.org/schema/context"   xmlns:p="http://www.springframework.org/schema/p"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/bean       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd       http://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-4.0.xsd      http://www.springframework.org/schema/aop   http://www.springframework.org/schema/aop/spring-aop-4.0.xsd     http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- Database connection pool -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- drive -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- url -->
<property name="url" value="jdbc:mysql://localhost:3306/ssmtest"/>
<!-- user name -->
<property name="username" value="root"/>
<!-- password -->
<property name="password" value="root"/></bean>
<!-- mapper to configure --> <!-- Give Way spring Administration sqlsessionfactory use mybatis and spring In the consolidation package -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!-- Database connection pool -->
<property name="dataSource" ref="dataSource"/>
<!--Creates aliases for all entity classes under the specified package-->
<property name="typeAliasesPackage" value="com.itheima.ssm.pojo"/></bean>
<!-- mapper Scanner: used to generate proxy objects-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.ssm.dao"></property>  
</bean>
</beans>

The spring configuration file is written in applicationContext-service.xml

④ Add spring MVC related configuration

Presentation layer Controller writing

@Controller
@RequestMapping("/item")
public class ItemController {
   @Autowired
   private ItemService itemService;
  @RequestMapping("/showItem/{id}")
  public String showItem(@PathVariable("id") int id, Model model){
        Item item = itemService.findById(id);
        model.addAttribute("item",item);
        return "item";   
  }
}

Spring mvc.xml file writing

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd       http://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-4.0.xsd">    <context:component-scan base-package="com.itheima.ssm.controller"/>
<!--  Configure the prefix and suffix of the view parser -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">           <property name="prefix" value="/WEB-INF/jsp/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
</beans>

jsp page writing

Configure the web.xml file

4. Build maven project by module

4.1 sub module construction maven engineering analysis

In real life, when automobile manufacturers produce automobiles, because the whole production process is very complex and cumbersome and the workload is very large, the parking lot will produce the parts of the whole automobile separately, and finally assemble the produced parts to form a complete automobile.

4.2 inheritance of Maven project

In the Java language, classes can inherit. Through inheritance, subclasses can reference non private properties and methods in the parent class. Similarly, maven projects can inherit from each other. After the child project inherits the parent project, the dependency introduced in the parent project can be used. The purpose of inheritance is to eliminate duplicate code.

4.3 aggregation of Maven project

In the pom.xml file of maven project, tags can be used to aggregate other maven projects. The purpose of aggregation is to carry out unified operation.

For example, there are multiple maven projects after splitting. If you want to package, you need to execute the packaging command for each project, which is very cumbersome. At this time, you can use tags to aggregate these projects into maven projects. When packaging is needed, you only need to execute the packaging command in this project once, and the aggregated projects under it will be packaged.

4.4 specific implementation of maven project of sub module construction

① Parent project maven_parent build

 <properties>
        <spring.version>5.0.5.RELEASE</spring.version>
        <springmvc.version>5.0.5.RELEASE</springmvc.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>
    <!--locking jar edition-->
    <dependencyManagement>
        <dependencies>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- springMVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${springmvc.version}</version>
            </dependency>
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

② Subproject maven_pojo build

pom.xml

<dependencies>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
</dependencies>

③ 3.1 subproject maven_dao construction

3.2 configuring maven_ pom.xml file of Dao project

 <dependencies>
        <dependency>
            <groupId>com.itheima</groupId>
            <artifactId>maven_pojo</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- Mybatis and mybatis And spring Integration of -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- MySql drive -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!-- druid Database connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- spring relevant -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <!-- junit test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

3.3 create DAO interface and Mapper mapping file

package com.itheima.ssm.dao;

import com.itheima.ssm.pojo.Item;

public interface ItemMapper {
    public Item findById(int id);
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.ssm.dao.ItemMapper">
    <select id="findById" parameterType="int" resultType="Item">
        select * from item where id = #{id}
    </select>
</mapper>

3.4 create the spring configuration file applicationContext-dao.xml in the resources directory

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context
						   http://www.springframework.org/schema/context/spring-context.xsd
						   http://www.springframework.org/schema/aop
						   http://www.springframework.org/schema/aop/spring-aop.xsd
						   http://www.springframework.org/schema/tx
						   http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--Configure data source information, using druid Connection pool-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssmtest"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--to configure spring integration mybatis Framed SQLSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--scanning pojo Package to create an alias for the entity class-->
        <property name="typeAliasesPackage" value="com.itheima.ssm.pojo"/>
    </bean>

    <!--mapper Scanner for generating proxy objects-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.ssm.dao"/>
    </bean>
</bean

④ Subproject maven_service build

Step 1: create maven_service Engineering

Step 2: configure maven_ pom.xml file of service project

<dependencies>
    <dependency>
        <groupId>com.itheima</groupId>
        <artifactId>maven_dao</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

Step 3: create Service interface and implementation class

package com.itheima.ssm.service;

import com.itheima.ssm.pojo.Item;

public interface ItemService {
    public Item findById(int id);
}

package com.itheima.ssm.service;

import com.itheima.ssm.dao.ItemMapper;
import com.itheima.ssm.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;

    public Item findById(int id) {
        return itemMapper.findById(id);
    }
}

Step 4: create the spring configuration file applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context
						   http://www.springframework.org/schema/context/spring-context.xsd
						   http://www.springframework.org/schema/aop
						   http://www.springframework.org/schema/aop/spring-aop.xsd
						   http://www.springframework.org/schema/tx
						   http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--Configure scanner, scan Service-->
    <context:component-scan base-package="com.itheima.ssm.service"/>

    <!--Transaction manager-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--Thing annotation driven-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

⑤ Subproject maven_web construction

Step 1: create maven_ For Web Engineering, note that the packaging method is war

Step 2: configure maven_ pom.xml file of Web project

<dependencies>
    <dependency>
        <groupId>com.itheima</groupId>
        <artifactId>maven_service</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>
</dependencies>

<build>
    <finalName>maven_web</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
        <plugins>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.1.0</version>
            </plugin>
            <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-install-plugin</artifactId>
                <version>2.5.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

Step 3: create Controller

package com.itheima.ssm.controller;

import com.itheima.ssm.pojo.Item;
import com.itheima.ssm.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @RequestMapping("/showItem/{id}")
    public String findById(@PathVariable("id") int id, Model model){
        Item item = itemService.findById(id);
        model.addAttribute("item",item);
        return "item";
    }
}

Step 4: create a jsp page

Step 5: configure web.xml

 <!--appoint Spring Profile location-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
  </context-param>

  <!--to configure Spring Listener used when the framework starts-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--to configure SpringMVC Front end controller-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

Step 6: create the springmvc configuration file springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context
						   http://www.springframework.org/schema/context/spring-context.xsd
						   http://www.springframework.org/schema/aop
						   http://www.springframework.org/schema/aop/spring-aop.xsd
						   http://www.springframework.org/schema/tx
						   http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--Configure scanner, scan Controller-->
    <context:component-scan base-package="com.itheima.ssm.controller"/>

    <!--view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

The overall structure of the project is as follows:

1)maven_ The parent project is the parent project, and the other projects are child projects, which inherit the parent project maven_parent

2)maven_ The parent project aggregates all its sub projects

3) There are dependencies between subprojects, such as maven_dao dependency, maven_pojo,maven_service depends on maven_dao, maven_web dependency maven_service

5. maven private service

5.1 private server description

Maven warehouse is divided into local warehouse and remote warehouse, and remote warehouse is divided into Maven central warehouse, other remote warehouses and private servers (private servers). Among them, the central warehouse is officially provided by maven, and the private server needs to be built by ourselves.

maven private server is the maven remote warehouse in the company's LAN. Each employee's computer installs maven software and connects to maven private server. Programmers can type their own projects into jars and publish them to the private server, and other project team members can download the dependent jars from the private server. The private server also acts as a proxy server. When there is no jar package on the private server, it will be automatically downloaded from the maven central warehouse.

Nexus is a maven Warehouse Manager (actually a software). Nexus can act as a maven private server. At the same time, nexus also provides powerful warehouse management, component search and other functions.

5.2 build maven private server

① Download nexus

https://help.sonatype.com/repomanager2/download/download-archives—repository-manager-oss

② Install nexus

Unzip the downloaded compressed package and enter the bin directory

Open the cmd window and enter the bin directory above, execute the nexus.bat install command to install the service (note that you need to run the cmd command as an administrator)

③ Start nexus

The nexus installation has been completed through the previous command. You can start the nexus service in the following two ways:

Start nexus in Windows system services

Execute the nexus.bat start command on the command line to start nexus

④ Access nexus

After starting the nexus service, access http://localhost:8081/nexus

Click the LogIn button in the upper right corner to log in. Log in to the system with the default user name admin and password admin123

After successful login, click Repositories on the left menu to see the list of nexus built-in warehouses (as shown in the figure below)

nexus warehouse type

As can be seen from the warehouse list above, nexus has many built-in warehouses by default. These warehouses can be divided into four types. Each type of warehouse is used to store specific jar packages. The details are as follows:

① Hosted, the hosted warehouse, deploys its own jar s to this type of warehouse, including releases and Snapshots. Releases is the company's internal release version warehouse and Snapshots is the company's internal test version warehouse

② Proxy, proxy warehouse, is used to proxy remote public warehouses, such as maven central warehouse. Users connect to private servers. Private servers automatically go to the central warehouse to download jar packages or plug-ins

③ Group, warehouse group, is used to merge multiple hosted/proxy warehouses. Usually, we configure our own maven connection warehouse group

④ Virtual: jar or plug-in compatible with Maven 1 version

Correspondence between nexus warehouse type and installation directory

5.3 publish the project to maven private server

Maven private server is a maven warehouse built in the company's LAN, which can be used by all development teams in the company. For example, if the technology R & D team develops a basic component, it can make a jar package and publish it to the private server. Other team members can download the jar package from the private server to the local warehouse and use it in the project.

The steps to publish the project to maven private server are as follows:

  1. Configure maven's settings.xml file
<server>
<id>releases</id>
<username>admin</username>   
<password>admin123</password>
</server>
<server>
<id>snapshots</id>
<username>admin</username>
<password>admin123</password>
</server>

Note: it must be configured in maven's settings.xml file introduced in idea tool

  1. pom.xml file for configuration project
<distributionManagement>
<repository>
   <id>releases</id>
   <url>http://localhost:8081/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
   <id>snapshots</id>               <url>http://localhost:8081/nexus/content/repositories/snapshots/</url>    </snapshotRepository>
</distributionManagement>
  1. Execute the mvn deploy command

5.4 download jar from private server to local warehouse

Previously, we have finished printing local projects into jar packages and publishing them to maven private server. Next, we need to download jar packages from maven private server to the local warehouse.

The specific operation steps are as follows:

Configure the download template in maven's settings.xml file

<profile>
	<id>dev</id>
		<repositories>
		<repository>
			<id>nexus</id>
		<!--Warehouse address, i.e nexus Address of warehouse group-->
			<url>
			http://localhost:8081/nexus/content/groups/public/</url>
		<!--Download releases component-->
			<releases>
			<enabled>true</enabled>
			</releases>
		<!--Download snapshots component-->
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		</repositories>
<pluginRepositories>
	<!-- Plug in warehouse, maven The operation of depends on the plug-in, and you also need to download the plug-in from the private server -->
	<pluginRepository>
		<id>public</id>
		<name>Public Repositories</name>
		<url>
		http://localhost:8081/nexus/content/groups/public/</url>
		</pluginRepository>
		</pluginRepositories>
</profile>

Configure the activation download template in maven's settings.xml file

<activeProfiles>
	<activeProfile>dev</activeProfile>
</activeProfiles>

6. Install the third-party jar into the local warehouse and maven private server

After configuring the coordinates of a jar package in the pom.xml file of the Maven project, if the jar package does not exist in the local Maven warehouse, the Maven tool will automatically download it to the configured Maven private server. If it does not exist in the private server, the Maven private server will download it from the maven central warehouse.

However, not all jar packages can be downloaded from the central warehouse. For example, the commonly used Oracle database driven jar packages do not exist in the central warehouse. At this time, you need to download the driver jar package from Oracle's official website, and then install the jar package into our local maven warehouse or maven private server through maven command, so that you can use maven coordinates to reference this jar package in maven project.

6.1 install the third-party jar into the local warehouse

① Download Oracle jar package (omitted)

② Install with the mvn install command

​ mvn install:install-file -Dfile=ojdbc14-10.2.0.4.0.jar -DgroupId=com.oracle -DartifactId=ojdbc14 –

​ Dversion=10.2.0.4.0 -Dpackaging=jar

③ Check the local maven warehouse and confirm whether the installation is successful

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-5Rrvq5Gp-1635002344356)(.\img \ picture 24.png)]

6.2 install the third-party jar into maven private server

① Download Oracle jar package (omitted)

② Configure the server information of the third-party warehouse in maven's settings.xml configuration file

<server>
  <id>thirdparty</id>
  <username>admin</username>
  <password>admin123</password>
</server>

③ Execute the mvn deploy command to install

​ mvn deploy:deploy-file -Dfile=ojdbc14-10.2.0.4.0.jar -DgroupId=com.oracle -DartifactId=ojdbc14 –

​ Dversion=10.2.0.4.0 -Dpackaging=jar –

​ Durl=http://localhost:8081/nexus/content/repositories/thirdparty/ -DrepositoryId=thirdparty

Keywords: SSM

Added by bouba on Sat, 23 Oct 2021 18:33:00 +0300