IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Maven的配置及使用 -> 正文阅读

[Java知识库]Maven的配置及使用

一、关于Maven

1.Maven的概念

Maven 是?个项?构建?具,创建的项?只要遵循 Maven 规范(称为Maven项?),即可使? Maven 来进?:管理 jar 包、编译项?,打包项?等功能。
为什么学习 Servlet 之前要学 Maven?
因为 Servlet 是框架,要使? Maven 进? jar 包管理和项?打包和发布。

2.Maven的作用

  1. 导?外部 jar 包
  2. 打包项?
  3. 发布项?

二、Maven的配置及使用

Maven ?需安装,因为 Idea 已经?带了,打开 Idea 的设置页面settings,在搜索框中输入“Maven”就能找到 Maven,如下图所示:
在这里插入图片描述
在这里插入图片描述

1.Maven 依赖管理流程

Maven 项?中可以引?依赖包(引?外部框架的 jar 包),引?后,加载依赖包的?式为在 Maven 仓库 中搜索。
Maven仓库可以理解为存放依赖包的仓库,分为本地仓库和远程仓库两种。
在这里插入图片描述
本地仓库地址在 Idea 中可以找到,如下图所示:
在这里插入图片描述

2.Maven的配置

Maven的数据源默认是国外的数据源,所以下载 jar 会很慢,且经常出差,所以?定要配置本机的 Maven 源 为国内源,它的配置?法如下:
1.找到maven的settings.xml配置文件
默认情况下电脑上有这个文件。
如果没有,解决方法如下:
复制settings.xml文件名,这里不建议手写,因为手写出错的可能性更大,会导致后面下载jar包失败。
在这里插入图片描述

【注】:配置文件目录是不能出现中文的。 如果出现中文字符,需要在Users的下一级目录新建xx\.m2文件,一定要改成英文文件名。

在配置文件目录的.m2文件中新建settings.xml文件
在这里插入图片描述
将下列代码复制到settings.xml文件中。

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

2.打开settings.xml文件,找到镜像,将下列代码复制到镜像集合中并保存。

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

在这里插入图片描述
这段代码的意思是配置国内源,现在使用最多的是阿里的源和网易的源,这里配置的是阿里的源(maven.aliyun.com),当下载jar包的时候从url所定义的网站进行下载。

3.勾选Idea中配置文件和本地仓库的Override
在这里插入图片描述
之后点击OK即可。
这一步设置完成后仅仅是设置了当前项目的配置信息,当打开一个新项目后,需要重新配置,很麻烦。所以需要进行下一步的设置。

3.配置新项目的maven国内源
在这里插入图片描述
重复前面的操作配置新项目的maven国内源。
在这里插入图片描述

三、新建maven项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

四、添加外部jar包

以jdbc的jar包为例。

1.查找依赖信息

在mvn中央仓库(相当于应用商城,所有开发者所需的jar包都在这里),找到对应的依赖信息。
中央仓库的地址如下:
https://mvnrepository.com/
在这里插入图片描述
根据本地电脑mysql的版本选择一个对应版本,点击进入。
在这里插入图片描述

2.添加依赖至pom.xml

复制maven的依赖信息到Idea项目的pom.xml里。
在这里插入图片描述
在这里插入图片描述

3.加载依赖

点击加载按钮,重新加载当前项目的依赖。
在这里插入图片描述
在这里插入图片描述

4.代码测试

连接本地数据库,查询信息。

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class App {
    public static void main(String[] args) throws SQLException {

        //1.得到DataSource
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setURL("jdbc:mysql://127.0.0.1:3306/java33?character=utf-8&useSSL=true");
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        //2.得到Connection
        Connection connection = (Connection) dataSource.getConnection();
        //3.拼接sql并执行
        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,2);
        //4.执行查询
        ResultSet resultSet = statement.executeQuery();
        if(resultSet.next()){
            //表示有数据
            System.out.println("用户名: "+ resultSet.getString("username"));
            System.out.println("邮箱:"+ resultSet.getString("mail"));
        }

        //5.关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

运行结果:
在这里插入图片描述
代码成功运行,说明依赖已经成功地添加到项目当中,并且可以正常使用。

五、Maven项目jar导入失败解决方案

1.检查配置

①检查Maven下的settings.xml是否配置并勾选了国内源
在这里插入图片描述
②检查settings.xml文件里是否设置了阿里云的镜像
在这里插入图片描述

2.删除jar包

打开本地仓库,删除里面包含的所有jar包。
在这里插入图片描述
在这里插入图片描述

3.使用Maven重新生成依赖

如果经过前三个步骤仍然存在错误,那么更换网络,继续进行前三步的操作,直至没有问题为止。

六、Maven生命周期

Maven构建?具主要?的就是对Maven项?进?管理,这些都是通过Maven的?命周期命令来管 理的。在IDEA创建的Maven项?中,打开Maven?板,展开项?的Lifecycle即为?命周期命令:
在这里插入图片描述

  • clean: 清空之前编译生成的临时文件

当一个java文件编译之后,会生成相应的字节码文件target,clean用于删除该字节码文件。
在这里插入图片描述

  • validate:验证合法性
    验证pom.xml是否正确,以及依赖是否都已经下载好了。
  • compile:编译
    自动调用javac把你的代码中的.java都编译成.class。
  • test:单元测试
    自动执行test这个目录中的单元测试代码(一般是搭配junit 来完成的)。
  • package:(最常用的)进行打包
  • verify:确认
    也是一个校验动作,往往是对测试结果进行检测。(集成测试)
  • install:安装.
    把你程序部署到某个本地的目录中,供其他程序使用。
  • site: 生成网站的报告信息。
  • deploy: 部署到中央仓库。
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-05-21 18:48:02  更:2022-05-21 18:49:33 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/28 3:49:01-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码