Maven 基础使用

参考 & 推荐

配置maven的中央库

因为种种原因, 使用国内的源会快很多, 所以这一步先做好比较省时间.
编辑~/.m2/settings.xml, 没有该文件的话直接创建即可.

gedit ~/.m2/settings.xml # 直接复制下面这段内容即可
<?xml version="1.0" encoding="UTF-8"?>
<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">

    <proxies>
        <proxy>
            <id>ss</id>
            <active>true</active>
            <protocol>socks5</protocol>
            <username></username>
            <password></password>
            <host>127.0.0.1</host>
            <port>1080</port>
            <nonProxyHosts>127.0.0.1</nonProxyHosts>
        </proxy>
    </proxies>

    <mirrors>
        <!-- 阿里云仓库 -->
        <mirror>
            <id>alimaven</id>
            <mirrorOf>central</mirrorOf>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
        </mirror>
    <!--
        
        <mirror>
            <id>repo1</id>
            <mirrorOf>central</mirrorOf>
            <name>Human Readable Name for this Mirror.</name>
            <url>http://repo1.maven.org/maven2/</url>
        </mirror>
    

        <mirror>
            <id>repo2</id>
            <mirrorOf>central</mirrorOf>
            <name>Human Readable Name for this Mirror.</name>
            <url>http://repo2.maven.org/maven2/</url>
        </mirror>
    -->
    </mirrors> 
</settings>



约定的目录格式

假设当前项目的根目录是App.

  • App
    • pom.xml
      maven项目的配置文件, 每个项目应该只有一个pom.xml
    • source code
      src/main/java
      存放源代码
    • resources
      src/main/resources
      资源文件, 比如说MyBatis等的XML配置文件. 该目录下的文件编译之后会被复制到target/classes目录中, 所以在代码中直接用getResourceAsStrem()方法就能得到相应的资源文件.
    • Test
      src/test
      存放测试用例
    • target
      target
      存放各种目标文件
    • target/classes
      target/classes
      存放编译后的classresources文件夹中的文件.
      class按照package建立相应的目录结构
      src/main/resources文件夹中的文件和目录被拷贝到该目录下, 比如说有src/main/resources/spring/config.xmlsrc/main/resources/user.properties文件在src/main/resources目录下, 那么编译之后target/classes中就会有spring/config.xmluser.properties.

pom.xml基本配置

最简单配置

<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>me.xiaofud</groupId>
  <artifactId>mabatis-learning</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

</project>
  • 根元素是<project>

You need to specify the basic schema settings such as apache schema and w3.org specification.

  • Model version
    写4.0.0即可
  • groupId
    类似包名

This is an Id of project's group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects.

  • artifactId

This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact's location within the repository.

  • version

This is the version of the project. Along with the groupId, It is used within an artifact's repository to separate versions from each other. For example,

  • com.company.bank:consumer-banking:1.0
  • com.company.bank:consumer-banking:1.1.

添加依赖

往pom.xml文件中加了<dependencies>, 其中添加了junitmybatis以及mysql-connector-java的依赖. 添加依赖的最基本设置, 就是在<dependencies>内添加<dependency>. 然后输入该依赖的groupdId, artifactId, 以及version即可. 依赖的这些属性可以到maven中央仓库搜索, 然后将groudId这些配置信息复制过来即可.

<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>me.xiaofud</groupId>
  <artifactId>mabatis-learning</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <!--The full name of the project.-->
  <name>mabatis-learning</name>
  <!--URL-->
  <url>your web site here</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>


  </dependencies>
</project>

mvn compile 命令

src/main/java中写几个Java类, 然后往src/main/resources文件中加一些资源文件, 就能很快使用maven进行一次编译. 将命令行的工作目录设定到项目的根目录, 输入:

mvn compile

即可执行编译.
输出结果:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building mabatis-learning 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ mabatis-learning ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 5 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.2:compile (default-compile) @ mabatis-learning ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 9 source files to /home/smallfly/programming_projects/java/spring/mabatislearning/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.377 s
[INFO] Finished at: 2017-11-07T23:51:47+08:00
[INFO] Final Memory: 13M/156M
[INFO] ------------------------------------------------------------------------

此时发现当前目录下出现了target文件夹, 里面的目录树如下:

target/
├── classes
│   ├── mapping
│   │   ├── job-mapper.xml
│   │   └── syllabus-mapper.xml
│   ├── me
│   │   └── xiaofud
│   │       ├── dao
│   │       │   ├── JobDao.class
│   │       │   └── SyllabusDao.class
│   │       ├── entity
│   │       │   ├── Comment.class
│   │       │   ├── Job.class
│   │       │   ├── Post.class
│   │       │   └── User.class
│   │       └── tests
│   │           ├── JobDaoTest.class
│   │           ├── SyllabusTest.class
│   │           └── TestWithoutXML.class
│   ├── mybatis-config.xml
│   ├── mybatis-syllabus-config.xml
│   └── properties
│       └── database.properties

对比src/main文件

src/
├── main
│   ├── java
│   │   └── me
│   │       └── xiaofud
│   │           ├── dao
│   │           │   ├── JobDao.java
│   │           │   └── SyllabusDao.java
│   │           ├── entity
│   │           │   ├── Comment.java
│   │           │   ├── Job.java
│   │           │   ├── Post.java
│   │           │   └── User.java
│   │           └── tests
│   │               ├── JobDaoTest.java
│   │               ├── SyllabusTest.java
│   │               └── TestWithoutXML.java
│   └── resources
│       ├── mapping
│       │   ├── job-mapper.xml
│       │   └── syllabus-mapper.xml
│       ├── mybatis-config.xml
│       ├── mybatis-syllabus-config.xml
│       └── properties
│           └── database.properties
└── test
    └── java
        └── me
            └── xiaofud
                └── AppTest.java

使用maven生成WAR文件, 方便直接部署到Web容器中运行.

Maven-war-plugin/usage

项目结构

├── pom.xml
├── springmvc101.iml
└── src
    └── main
        ├── java
        │   └── me
        │       └── xiaofud
        │           └── spring101
        │               └── controllers
        │                   └── MainController.java
        ├── resources
        │   └── dispatcher-servlet.xml
        ├── test
        └── webapp
            ├── index.html
            ├── index.jsp
            └── WEB-INF
                └── web.xml

pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>me.xiaofud</groupId>
  <artifactId>springmvc101</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springmvc101 Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>4.3.8.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>4.3.8.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
          <version>4.3.8.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.3.8.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.3.8.RELEASE</version>
      </dependency>


  </dependencies>

  <build>
    <finalName>springmvc101</finalName>
  </build>

</project>

注意<packaging>war</packaging>, 指明了打包目标为war类型.
pom.xml所在目录, 直接运行:

mvn package

输出:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building springmvc101 Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ springmvc101 ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.2:compile (default-compile) @ springmvc101 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /home/smallfly/programming_projects/java/spring/springmvc101/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.3:testResources (default-testResources) @ springmvc101 ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/smallfly/programming_projects/java/spring/springmvc101/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.2:testCompile (default-testCompile) @ springmvc101 ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.17:test (default-test) @ springmvc101 ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ springmvc101 ---
[INFO] Packaging webapp
[INFO] Assembling webapp [springmvc101] in [/home/smallfly/programming_projects/java/spring/springmvc101/target/springmvc101]
[INFO] Processing war project
[INFO] Copying webapp resources [/home/smallfly/programming_projects/java/spring/springmvc101/src/main/webapp]
[INFO] Webapp assembled in [56 msecs]
[INFO] Building war: /home/smallfly/programming_projects/java/spring/springmvc101/target/springmvc101.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.125 s
[INFO] Finished at: 2017-11-09T00:04:25+08:00
[INFO] Final Memory: 18M/191M
[INFO] ------------------------------------------------------------------------

target目录结构:

├── classes
│   ├── dispatcher-servlet.xml
│   └── me
│       └── xiaofud
│           └── spring101
│               └── controllers
│                   └── MainController.class
├── maven-archiver
│   └── pom.properties
├── maven-status
│   └── maven-compiler-plugin
│       └── compile
│           └── default-compile
│               ├── createdFiles.lst
│               └── inputFiles.lst
├── springmvc101
│   ├── index.html
│   ├── index.jsp
│   ├── META-INF
│   └── WEB-INF
│       ├── classes
│       │   ├── dispatcher-servlet.xml
│       │   └── me
│       │       └── xiaofud
│       │           └── spring101
│       │               └── controllers
│       │                   └── MainController.class
│       ├── lib
│       │   ├── aspectjweaver-1.8.9.jar
│       │   ├── commons-logging-1.2.jar
│       │   ├── hamcrest-core-1.3.jar
│       │   ├── junit-4.12.jar
│       │   ├── spring-aop-4.3.8.RELEASE.jar
│       │   ├── spring-aspects-4.3.8.RELEASE.jar
│       │   ├── spring-beans-4.3.8.RELEASE.jar
│       │   ├── spring-context-4.3.8.RELEASE.jar
│       │   ├── spring-core-4.3.8.RELEASE.jar
│       │   ├── spring-expression-4.3.8.RELEASE.jar
│       │   ├── spring-web-4.3.8.RELEASE.jar
│       │   └── spring-webmvc-4.3.8.RELEASE.jar
│       └── web.xml
└── springmvc101.war

可以看到, mvn帮我们生成了war文件, 以及war-exploded形式的文件夹(springmvc101).
我们将.war文件或者war-exploded文件夹直接拷贝到Tomcat容器的webapps目录下, 即完成了部署.

如果packaging的值不是war

  • 使用war:war goal
mvn compile war:war # 将编译项目, 以及生成`war`和`war-exploded`
  • 使用war:exploded
mvn compile war:exploded # 仅仅生成`war-exploded`形式
  • 使用war:inplace

Another variation of war:exploded is war:inplace. With war:inplace the exploded WAR is created in the webapp source, which defaults to src/main/webapp

即将war-exploded存到src/main/webapp中.

mvn compile war:inplace

finalName

存放war-exploded的文件夹名称, 默认是target/<finalName>. 其中finalName<artifactId>-<version>, 可以被配置覆盖.
<build>标签中加入<finalName>标签, 即可覆盖该属性.

  <build>
    <finalName>springmvc101</finalName>
  </build>

mvn clean

用于删除上一次build过后产生的文件.

mvn archetype的简单使用

introduction-to-archetypes
archetype - usage
mkyong - How to create a Web Application Project with Maven
使用archetype可以快速创建指定类型的项目骨架.
以创建webapp骨架为例, 介绍使用mvn archetype的使用.
在希望存放项目的目录中运行:

mvn archetype:generate -DgroupId=your_group_id -DartifactId=your_project_name -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

如果希望进入交互模式创建项目, 那么直接mvn archetype:generate即可.
实例:

mvn archetype:generate -DgroupId=me.xiaofu.d -DartifactId=amazingapp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

生成的项目骨架:

tree amazingapp/

amazingapp/
├── pom.xml
└── src
    └── main
        ├── resources
        └── webapp
            ├── index.jsp
            └── WEB-INF
                └── web.xml
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,128评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,316评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,737评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,283评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,384评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,458评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,467评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,251评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,688评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,980评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,155评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,818评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,492评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,142评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,382评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,020评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,044评论 2 352

推荐阅读更多精彩内容