Maven 基礎使用

參考 & 推薦

配置maven的中央庫

因為種種原因, 使用國內的源會快很多, 所以這一步先做好比較省時間.
編輯~/.m2/settings.xml, 沒有該文件的話直接創(chuàng)建即可.

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

即可執(zhí)行編譯.
輸出結果:

[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] ------------------------------------------------------------------------

此時發(fā)現(xiàn)當前目錄下出現(xiàn)了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可以快速創(chuàng)建指定類型的項目骨架.
以創(chuàng)建webapp骨架為例, 介紹使用mvn archetype的使用.
在希望存放項目的目錄中運行:

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

如果希望進入交互模式創(chuàng)建項目, 那么直接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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末疤苹,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌段誊,老刑警劉巖猪钮,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件廊蜒,死亡現(xiàn)場離奇詭異枣宫,居然都是意外死亡夭织,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來抢腐,“玉大人姑曙,你說我怎么就攤上這事襟交÷醣叮” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵捣域,是天一觀的道長啼染。 經常有香客問我,道長焕梅,這世上最難降的妖魔是什么迹鹅? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮贞言,結果婚禮上斜棚,老公的妹妹穿的比我還像新娘。我一直安慰自己该窗,他們只是感情好弟蚀,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著酗失,像睡著了一般义钉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上规肴,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天捶闸,我揣著相機與錄音,去河邊找鬼拖刃。 笑死删壮,一個胖子當著我的面吹牛,可吹牛的內容都是我干的兑牡。 我是一名探鬼主播央碟,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼发绢!你這毒婦竟也來了硬耍?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤边酒,失蹤者是張志新(化名)和其女友劉穎经柴,沒想到半個月后蜡吧,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體橡娄,經...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年政恍,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片牛哺。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡陋气,死狀恐怖,靈堂內的尸體忽然破棺而出引润,到底是詐尸還是另有隱情巩趁,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布淳附,位于F島的核電站议慰,受9級特大地震影響,放射性物質發(fā)生泄漏奴曙。R本人自食惡果不足惜别凹,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望洽糟。 院中可真熱鬧炉菲,春花似錦、人聲如沸坤溃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽浇雹。三九已至沉御,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間昭灵,已是汗流浹背吠裆。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留烂完,地道東北人试疙。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像抠蚣,于是被迫代替她去往敵國和親祝旷。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內容