项目管理及自动构建工具Maven

一、Maven安装、目录结构、cmd命令
1.下载安装
apache-maven-3.2.3-bin.zip
下载:http://maven.apache.org/download.cgi


安装:解压,配置环境变量
M2_HOME=D:\Idea\config\apache-maven-3.2.3
Path+=D:\Idea\config\apache-maven-3.2.3\bin

通过执行 mvn -v 可以查看当前版本号

C:\Users\yuki>mvn -v
Apache Maven  (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; --12T04::+:)
Maven home: D:\Idea\config\apache-maven-
Java version: , vendor: Oracle Corporation
Java home: C:\Java\jdk1.8.0\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 8.1", version: "6.3", arch: "x86", family: "dos"

这样,maven就安装好了

2.编译:mvn compile
新建文件D:\Maven\app1-maven\pom.xml
http://maven.apache.org/pom.html
复制project、modelVersion标签到文件中

<?xml version="1.0" encoding="UTF-8"?>
<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>yuki.maven.app1</groupId>
    <!-- 模块 -->
    <artifactId>module1</artifactId>
    <!-- 版本 -->
    <version>0.0.1-SNAPSHOT</version>

    <!-- 依赖 -->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>

</project>

groupId:表示项目
artifactId:表示模块
version:表示版本

在D:\Maven\app1-maven\src下新建文件夹main,test
新建文件D:\Maven\app1\module1\src\main\java\yuki\maven\app1\module1\HelloMaven.java

package yuki.maven.app1.module1;

public class HelloMaven
{
    public String sayHello(String name){
        return "hello:" + name;
    }
}

cmd进入文件夹D:\Maven\app1-maven
执行命令:mvn compile,会看到一直在运行Downloaded

C:\Users\yuki>D:

D:\>cd D:\Maven\app1\module1

D:\Maven\app1\module1>mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 -SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module1 ---
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-container-default//plexus-container-de
fault-.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-container-default//plexus-container-def
ault-.pom ( KB at 0.7 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils//plexus-utils-.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils//plexus-utils-.pom ( KB at
2.8 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-classworlds//plexus-classworlds-.
pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-classworlds//plexus-classworlds-.p
om ( KB at 5.1 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/xbean/xbean-reflect/3.4/xbean-reflect-3.4.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/xbean/xbean-reflect/ KB at 3.7 K
B/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/xbean/xbean/3.4/xbean-3.4.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/xbean/xbean/ KB at 16.8 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/log4j/log4j//log4j-.pom
Downloaded: https://repo.maven.apache.org/maven2/log4j/log4j//log4j-.pom ( B at 0.2 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/commons-logging/commons-logging-api/1.1/commons-logging-api-1.1.pom
Downloaded: https://repo.maven.apache.org/maven2/commons-logging/commons-logging-api/
KB at 6.5 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/com/google/collections/google-collections/1.0/google-collections-1.0.p
om
Downloaded: https://repo.maven.apache.org/maven2/com/google/collections/google-collections/1.0/google-collections-1.0.po
m ( KB at 3.1 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/com/google/google//google-.pom
Downloaded: https://repo.maven.apache.org/maven2/com/google/google//google-.pom ( KB at 1.9 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/junit/junit//junit-.pom
Downloaded: https://repo.maven.apache.org/maven2/junit/junit//junit-.pom ( B at 1.0 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils//plexus-utils-.jar
Downloading: https://repo.maven.apache.org/maven2/com/google/code/findbugs/jsr305//jsr305-.jar
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-utils/0.1/maven-shared-utils-0.1.
jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-component-annotations//plexus-componen
t-annotations-.jar
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-incremental/1.1/maven-shared-incr
emental-1.1.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-component-annotations//plexus-component
-annotations-.jar ( KB at 2.8 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/2.2/plexus-compiler-api-2.2.ja
r
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-incremental/1.1/maven-shared-incre
mental- KB at 6.8 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/2.2/plexus-compiler-manage
r-2.2.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/2.2/plexus-compiler-manager
- KB at 6.2 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/.
.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/2.2/plexus-compiler-api-2.2.jar
 ( KB at 20.4 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/xbean/xbean-reflect/3.4/xbean-reflect-3.4.jar
Downloaded: https://repo.maven.apache.org/maven2/com/google/code/findbugs/jsr305//jsr305-.jar ( KB at 10.5 K
B/sec)
Downloading: https://repo.maven.apache.org/maven2/log4j/log4j//log4j-.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils//plexus-utils-.jar ( KB a
t 52.2 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/commons-logging/commons-logging-api/1.1/commons-logging-api-1.1.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/2.2/plexus-compiler-javac-2.2
.jar ( KB at 10.8 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/com/google/collections/google-collections/1.0/google-collections-1.0.j
ar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-utils/0.1/maven-shared-utils-0.1.j
ar ( KB at 34.0 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/junit/junit//junit-.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/xbean/xbean-reflect/ KB at .
 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/commons-logging/commons-logging-api/
 KB at 16.3 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/junit/junit//junit-.jar ( KB at 43.7 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/log4j/log4j//log4j-.jar ( KB at 65.6 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/com/google/collections/google-collections/1.0/google-collections-1.0.ja
r ( KB at 62.4 KB/sec)
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling  source file to D:\Maven\app1\module1\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30.990 s
[INFO] Finished at: --01T22::+:
[INFO] Final Memory: 12M/30M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module1>

maven会根据我们的需要在网络上下载相应的内容,运行完毕后,会看到Finished,
在模块根目录D:\Maven\app1\module1下看到文件夹target,这是生成的文件

3.测试:mvn test
新建文件D:\Maven\app1\module1\src\test\java\yuki\maven\app1\module1\TestHelloMaven.java

package yuki.maven.app1.module1;

import org.junit.*;
import static org.junit.Assert.*;

public class TestHelloMaven
{
    @Test
    public void testSayHello(){
        HelloMaven maven = new HelloMaven();
        String str = maven.sayHello("maven");
        assertEquals(str, "hello:maven");
        //assertEquals(str, "hello:maven1");
    }
}

在pom.xml中添加依赖junit
执行mvn test

D:\Maven\app1\module1>mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module1 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ module1 ---
[INFO] Surefire report directory: D:\Maven\app1\module1\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running yuki.maven.app1.TestHelloMaven
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.125 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.819 s
[INFO] Finished at: 2014-09-01T23:06:34+08:00
[INFO] Final Memory: 11M/28M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module1>

通过在配置文件引入junit的jar就可以使用它编译
把项目按照maven的要求的目录中,
它就会自动根据pom.xml文件对项目进行编译、测试、发布等操作

通过maven就可以自动完成编译,把编译后的文件放到target中,
在测试后,会在D:\Maven\app1\module1\target\surefire-reports生成测试报告

D:\Maven\app1\module1\target\surefire-reports\yuki.maven.app1.module1.TestHelloMaven.txt

-------------------------------------------------------------------------------
Test set: yuki.maven.app1.module1.TestHelloMaven
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.098 sec

4.清空:mvn clean
执行后生成的target文件被删除了

把测试类修改为断言相等一定为假的语句
D:\Maven\app1\module1\target\surefire-reports\yuki.maven.app1.TestHelloMaven.txt
文件中,我们可以看到报错的信息

D:\Maven\app1\module1>mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5
.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.
pom (4 KB at 0.6 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/22/maven-plugins-22.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/22/maven-plugins-22.pom (13 KB a
t 20.1 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5
.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.
jar (25 KB at 18.7 KB/sec)
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ module1 ---
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.pom (4 KB at 6.0
KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/sonatype/spice/spice-parent/16/spice-parent-16.pom
Downloaded: https://repo.maven.apache.org/maven2/org/sonatype/spice/spice-parent/16/spice-parent-16.pom (9 KB at 11.5 KB
/sec)
Downloading: https://repo.maven.apache.org/maven2/org/sonatype/forge/forge-parent/5/forge-parent-5.pom
Downloaded: https://repo.maven.apache.org/maven2/org/sonatype/forge/forge-parent/5/forge-parent-5.pom (9 KB at 11.7 KB/s
ec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.jar (221 KB at 77
.9 KB/sec)
[INFO] Deleting D:\Maven\app1\module1\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 14.236 s
[INFO] Finished at: 2014-09-01T23:17:37+08:00
[INFO] Final Memory: 5M/17M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module1>mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ module1 ---
[INFO] Surefire report directory: D:\Maven\app1\module1\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running yuki.maven.app1.TestHelloMaven
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.114 sec <<< FAILURE!
testSayHello(yuki.maven.app1.TestHelloMaven)  Time elapsed: 0.024 sec  <<< FAILURE!
org.junit.ComparisonFailure: expected:<hello:maven[]> but was:<hello:maven[1]>
        at org.junit.Assert.assertEquals(Assert.java:125)
        at org.junit.Assert.assertEquals(Assert.java:147)
        at yuki.maven.app1.TestHelloMaven.testSayHello(TestHelloMaven.java:13)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

Results :

Failed tests:   testSayHello(yuki.maven.app1.TestHelloMaven): expected:<hello:maven[]> but was:<hello:maven[1]>

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.410 s
[INFO] Finished at: 2014-09-01T23:20:49+08:00
[INFO] Final Memory: 12M/29M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project modu
le1: There are test failures.
[ERROR]
[ERROR] Please refer to D:\Maven\app1\module1\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
D:\Maven\app1\module1>

5.打包:mvn package
执行mvn clean后,执行mvn package

D:\Maven\app1\module1>mvc clean
'mvc' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

D:\Maven\app1\module1>mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ module1 ---
[INFO] Deleting D:\Maven\app1\module1\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.530 s
[INFO] Finished at: 2014-09-01T23:26:50+08:00
[INFO] Final Memory: 5M/15M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module1>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-jar-plugin/2.4/maven-jar-plugin-2.4.pom

Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-jar-plugin/2.4/maven-jar-plugin-2.4.pom
(6 KB at 2.3 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-jar-plugin/2.4/maven-jar-plugin-2.4.jar

Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-jar-plugin/2.4/maven-jar-plugin-2.4.jar
(34 KB at 23.9 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ module1 ---
[INFO] Surefire report directory: D:\Maven\app1\module1\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running yuki.maven.app1.TestHelloMaven
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.099 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ module1 ---
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/2.5/maven-archiver-2.5.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/2.5/maven-archiver-2.5.pom (5 KB at 6.6
 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.pom (3 KB a
t 4.7 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.pom (2 KB at 3.0 KB
/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-components/1.1.19/plexus-components-1.1.19.
pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-components/1.1.19/plexus-components-1.1.19.p
om (3 KB at 4.5 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/3.0.1/plexus-3.0.1.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/3.0.1/plexus-3.0.1.pom (19 KB at 26.7 KB/sec
)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.15/plexus-interpolation-1.1
5.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.15/plexus-interpolation-1.15
.pom (1018 B at 1.1 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.pom
Downloaded: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.pom (10 KB at 15.8 KB/se
c)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/2.5/maven-archiver-2.5.jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.15/plexus-interpolation-1.1
5.jar
Downloading: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/2.5/maven-archiver-2.5.jar (22 KB at 19
.7 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.15/plexus-interpolation-1.15
.jar (60 KB at 34.3 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.jar (57 KB at 33.0
KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.jar (181 KB
 at 50.5 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.jar (203 KB at 51.6 KB/s
ec)
[INFO] Building jar: D:\Maven\app1\module1\target\module1-0.0.1-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.764 s
[INFO] Finished at: 2014-09-01T23:28:25+08:00
[INFO] Final Memory: 13M/31M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module1>

在target目录下会看到项目被打成了一个jar包

6.安装:mvn install
建立第二个模块module2
复制/app1/module1/pom.xml到/app1/module2下
新建文件:D:\Maven\app1\module2\src\main\java\yuki\maven\app1\module2\Hello.java

package yuki.maven.app1.module2;

import yuki.maven.app1.module1.HelloMaven;

public class Hello
{
    public String say(String name){
        HelloMaven maven = new HelloMaven();
        return maven.sayHello(name);
    }
}

在文件中引入module1中的HelloMaven中的类
在pom.xml的依赖中添加module1模块的坐标

回到module1中,执行mvn install

D:\Maven\app1\module1>mvn install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module1 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin
-2.4.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin-
2.4.pom (7 KB at 1.7 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin
-2.4.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin-
2.4.jar (27 KB at 17.0 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ module1 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module1\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ module1 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module1\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ module1 ---
[INFO] Surefire report directory: D:\Maven\app1\module1\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running yuki.maven.app1.module1.TestHelloMaven
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.102 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ module1 ---
[INFO] Building jar: D:\Maven\app1\module1\target\module1-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ module1 ---
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.5/plexus-utils-3.0.5.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.5/plexus-utils-3.0.5.pom (3 KB at
3.8 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/3.1/plexus-3.1.pom
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/3.1/plexus-3.1.pom (19 KB at 27.4 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.5/plexus-utils-3.0.5.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.5/plexus-utils-3.0.5.jar (226 KB a
t 76.9 KB/sec)
[INFO] Installing D:\Maven\app1\module1\target\module1-0.0.1-SNAPSHOT.jar to C:\Users\yuki\.m2\repository\yuki\maven\app
1\module1\0.0.1-SNAPSHOT\module1-0.0.1-SNAPSHOT.jar
[INFO] Installing D:\Maven\app1\module1\pom.xml to C:\Users\yuki\.m2\repository\yuki\maven\app1\module1\0.0.1-SNAPSHOT\m
odule1-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 15.142 s
[INFO] Finished at: 2014-09-02T00:01:36+08:00
[INFO] Final Memory: 14M/34M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module1>

回到module2中,执行mvc compile,编译通过

D:\Maven\app1\module1>cd ../module2

D:\Maven\app1\module2>mvn compile
[INFO] Scanning for projects...
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project yuki.maven.app1:module2:0.0.1-SNAPSHOT (D:\Maven\app1\module2\pom.xml) has 1 error
[ERROR]     'dependencies.dependency.version' for yuki.maven.app1:module1:jar is missing. @ line 24, column 15
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
D:\Maven\app1\module2>mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building module2 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module2 ---
[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Maven\app1\module2\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module2 ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding GBK, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\Maven\app1\module2\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.602 s
[INFO] Finished at: 2014-09-02T00:06:21+08:00
[INFO] Final Memory: 10M/26M
[INFO] ------------------------------------------------------------------------
D:\Maven\app1\module2>

7.maven的作用
可以把项目分成很多模块,把模块开发好,
将来直接用dependency把模块引入进来就可以直接用了

在项目中不需要再引入jar包,我们可以把项目打成jar包
所有的工作都可以由maven代劳

二、修改仓库路径、新建eclipse maven项目
1.仓库:repository
在用到jar文件或其它插件文件的时候,maven就会下载这些文件
这些文件放在默认放在C:\Users\yuki\.m2\repository中
当执行mvn compile的时候,
maven就会根据pom.xml的dependencies找到可能依赖的jar
如果仓库中不存在,就会在网络中下载,并把它放在仓库里

打开C:\Users\yuki\.m2\repository\junit\junit\4.10\junit-4.10.pom
会看到有关这个jar包的信息

<?xml version="1.0" encoding="UTF-8"?>
<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>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
    <name>JUnit</name>
    <url>http://junit.org</url>
    <description>
        JUnit is a regression testing framework written by Erich Gamma and Kent Beck.
        It is used by the developer who implements unit tests in Java.
    </description>
    <organization>
        <name>JUnit</name>
        <url>http://www.junit.org</url>
    </organization>
    <mailingLists>
        <mailingList>
            <name>JUnit Mailing List</name>
            <post>junit@yahoogroups.com</post>
            <archive>
                http://tech.groups.yahoo.com/group/junit/
            </archive>
        </mailingList>
    </mailingLists>
    <licenses>
        <license>
            <name>Common Public License Version 1.0</name>
            <url>http://www.opensource.org/licenses/cpl1.0.txt</url>
        </license>
    </licenses>
    <scm>
        <connection>scm:git:git://github.com/KentBeck/junit.git</connection>
        <developerConnection>scm:git:git@github.com:KentBeck/junit.git</developerConnection>
        <url>http://github.com/KentBeck/junit/tree/master</url>
    </scm>
    <developers>
      <developer>
        <id>dsaff</id>
        <name>David Saff</name>
        <email>david@saff.net</email>
      </developer>
    </developers>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <encoding>ISO-8859-1</encoding>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-core</artifactId>
          <version>1.1</version>
          <scope>compile</scope>
        </dependency>
    </dependencies>

    <properties>
         <jdk.version>1.5</jdk.version>
    </properties>
</project>

当执行mvn install后,会把生成的jar包发送至本地的仓库中
C:\Users\yuki\.m2\repository\yuki\maven\app1\module1\0.0.1-SNAPSHOT\module1-0.0.1-SNAPSHOT.jar


所以可以通过依赖引入jar包

2.自定义仓库的位置
把仓库放在系统盘中是不合适的,一旦重装系统,对应仓库就会消失
全球maven的中央仓库:http://mvnrepository.com/

打开文件${M2_HOME}\conf\settings.xml

搜索localRepository,看到Default: ${user.home}/.m2/repository

新建文件夹D:\Idea\maven\repository

  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
    <localRepository>D:\Idea\maven\repository</localRepository>

在setting.xml添加<localRepository>D:\Idea\maven\repository</localRepository>
执行mvn compile,会看到文件又在重新下载
可以把原先下载的文件的目录剪切到新的文件夹下,这样就不会重新下载了

它是怎么找到中央库的,打开文件
D:\Idea\config\apache-maven-3.2.3\lib\maven-model-builder-3.2.3.jar
查看\maven-model-builder-3.2.3.jar\org\apache\maven\model\pom-4.0.0.xml

 <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
    </pluginRepository>
  </pluginRepositories>

会看到设置了https://repo.maven.apache.org/maven2 的仓库url
用浏览器访问这个url,会跳转到http://search.maven.org/#browse

3.原型:mvn archetype
maven的目录结构是确定的,
执行 mvn archetype:generate 就会下载与这个原型相关的程序
下载完成后,文件被存在本地工厂中
版本号选择默认的6,groupId输入yuki.maven.app,
artifactId输入module,version输入0.0.1-SNAPSHOT
package默认,最后输入选择默认的Y
最后它在执行命令的根目录下帮我们建立了一个相似的module文件夹

918: remote -> org.openengsb.tooling.archetypes:openengsb-tooling-archetypes-connector (Archetype to produce new Connect
or project)
919: remote -> org.openengsb.tooling.archetypes:openengsb-tooling-archetypes-domain (Archetype to produce new Domain pro
ject)
920: remote -> org.openengsb.tooling.archetypes:org.openengsb.tooling.archetypes.connector (Archetype to produce new Con
nector project)
921: remote -> org.openengsb.tooling.archetypes:org.openengsb.tooling.archetypes.domain (Archetype to produce new Domain
 project)
922: remote -> org.openengsb.tooling.archetypes.clientproject:org.openengsb.tooling.archetypes.clientproject.root (Arche
type to produce new client project)
923: remote -> org.opengis.cite:ets-archetype-testng (A template for creating a new executable test suite (ETS) based on
 the TestNG framework.)
924: remote -> org.openjdk.jmh:jmh-groovy-benchmark-archetype (Generates Groovy benchmarking project, uses JMH bytecode
processors)
925: remote -> org.openjdk.jmh:jmh-java-benchmark-archetype (Generates Java benchmarking project, uses JMH annotation pr
ocessors)
926: remote -> org.openjdk.jmh:jmh-kotlin-benchmark-archetype (Generates Kotlin benchmarking project, uses JMH bytecode
processors)
927: remote -> org.openjdk.jmh:jmh-scala-benchmark-archetype (Generates Scala benchmarking project, uses JMH bytecode pr
ocessors)
928: remote -> org.openjdk.jmh:jmh-simple-benchmark-archetype (Basic archetype for simple JMH-driven benchmark.)
929: remote -> org.openl.rules:openl-simple-project (-)
930: remote -> org.openl.rules:openl-simple-project-archetype (-)
931: remote -> org.ops4j.pax.construct:maven-archetype-osgi-bundle (-)
932: remote -> org.ops4j.pax.construct:maven-archetype-osgi-project (-)
933: remote -> org.ops4j.pax.construct:maven-archetype-osgi-service (-)
934: remote -> org.ops4j.pax.construct:maven-archetype-osgi-wrapper (-)
935: remote -> org.ops4j.pax.construct:maven-archetype-spring-bean (-)
936: remote -> org.ops4j.pax.exam:maven-archetype-paxexam-junit ()
937: remote -> org.ops4j.pax.web.archetypes:wab-archetype (-)
938: remote -> org.ops4j.pax.web.archetypes:wab-gwt-archetype (-)
939: remote -> org.ops4j.pax.web.archetypes:war-archetype (-)
940: remote -> org.ow2.jasmine.kerneos:kerneos-module-archetype (-)
941: remote -> org.ow2.jasmine.kerneos:kerneos-war-archetype (-)
942: remote -> org.ow2.jasmine.probe:jprobe-collector-archetype (-)
943: remote -> org.ow2.jasmine.probe:jprobe-outer-archetype (-)
944: remote -> org.ow2.jonas.camel:camel-archetype-simple-route (-)
945: remote -> org.ow2.kerneos:kerneos-application-archetype (-)
946: remote -> org.ow2.kerneos:kerneos-flex-archetypes-application (-)
947: remote -> org.ow2.kerneos:kerneos-flex-archetypes-module (-)
948: remote -> org.ow2.kerneos:kerneos-flex-archetypes-module-fragment (-)
949: remote -> org.ow2.kerneos:kerneos-module-archetype (-)
950: remote -> org.ow2.orchestra:orchestra-extension-archetype (Generates extensions for Orchestra)
951: remote -> org.ow2.petals:maven-archetype-petals-jbi-binding-component (This project is Maven 2 archetype associated
 to a JBI binding component project.)
952: remote -> org.ow2.petals:maven-archetype-petals-jbi-service-assembly (This project is Maven 2 archetype associated
to a JBI service assembly project.)
953: remote -> org.ow2.petals:maven-archetype-petals-jbi-service-engine (This project is Maven 2 archetype associated to
 a JBI service engine project.)
954: remote -> org.ow2.petals:maven-archetype-petals-jbi-service-unit (This project is Maven 2 archetype associated to a
 JBI service unit project.)
955: remote -> org.ow2.petals:maven-archetype-petals-jbi-shared-library (This project is Maven 2 archetype associated to
 a JBI Shared Library project.)
956: remote -> org.ow2.shelbie:shelbie-command-archetype (-)
957: remote -> org.ow2.weblab.tools.maven:weblab-archetype-analyser (The Archetype used to generate a stub for analyser.
 This should be called through the weblab-archetype-plugin and not directly.)
958: remote -> org.ow2.weblab.tools.maven:weblab-archetype-configurable (The Archetype used to generate a stub for confi
gurable. This should be called through the weblab-archetype-plugin and not directly.)
959: remote -> org.ow2.weblab.tools.maven:weblab-archetype-indexer (The Archetype used to generate a stub for indexer. T
his should be called through the weblab-archetype-plugin and not directly.)
960: remote -> org.ow2.weblab.tools.maven:weblab-archetype-queuemanager (The Archetype used to generate a stub for queue
manager. This should be called through the weblab-archetype-plugin and not directly.)
961: remote -> org.ow2.weblab.tools.maven:weblab-archetype-reportprovider (The Archetype used to generate a stub for rep
ortprovider. This should be called through the weblab-archetype-plugin and not directly.)
962: remote -> org.ow2.weblab.tools.maven:weblab-archetype-resourcecontainer (The Archetype used to generate a stub for
resourcecontainer. This should be called through the weblab-archetype-plugin and not directly.)
963: remote -> org.ow2.weblab.tools.maven:weblab-archetype-resources (The Archetype used to generate a stub for any WebL
ab service. It should be used in conjunction with interfaces specific archetypes. This should be called through the webl
ab-archetype-plugin and not directly.)
964: remote -> org.ow2.weblab.tools.maven:weblab-archetype-searcher (The Archetype used to generate a stub for searcher.
 This should be called through the weblab-archetype-plugin and not directly.)
965: remote -> org.ow2.weblab.tools.maven:weblab-archetype-sourcereader (The Archetype used to generate a stub for sourc
ereader. This should be called through the weblab-archetype-plugin and not directly.)
966: remote -> org.ow2.weblab.tools.maven:weblab-archetype-trainable (The Archetype used to generate a stub for trainabl
e. This should be called through the weblab-archetype-plugin and not directly.)
967: remote -> org.parallelj:parallelj-archetype (ParallelJ is a Java framework for parallel computing. It provides flow
 modeling and execution. This archetype projects allows to create a project skeleton using ParallelJ.)
968: remote -> org.parallelj:parallelj-archetype-web (ParallelJ is a Java framework for parallel computing. It provides
flow modeling and execution. This archetype projects allows to create a project skeleton using ParallelJ.)
969: remote -> org.parancoe:parancoe-pluginarchetype (-)
970: remote -> org.parancoe:parancoe-webarchetype (-)
971: remote -> org.patterntesting:patterntesting-tools (PatternTesting Tools (patterntesting-tools) is the container for

    tools around PatternTesting like the Ant extensions and Maven plugin.)
972: remote -> org.pustefixframework:pustefix-archetype-application (Pustefix Archetype for Applications)
973: remote -> org.pustefixframework:pustefix-archetype-basic (Pustefix archetype creating a basic application)
974: remote -> org.pustefixframework.maven.archetypes:pustefix-archetype-module (Pustefix Archetype for Modules)
975: remote -> org.qianalyze:QiAnalyzeModule-Archetype (The archetype to create a new QiAnalyze Module for more informat
ion visit http://java.net/projects/qianalyze)
976: remote -> org.qianalyze.sample:QiAnalyzeModule (The archetype to create a new QiAnalyze Module for more information
 visit http://java.net/projects/qianalyze)
977: remote -> org.qooxdoo:qooxdoo-archetype-desktop (An archetype to create a qooxdoo application)
978: remote -> org.qooxdoo:qooxdoo-archetype-gui (An archetype to create a qooxdoo application)
979: remote -> org.quattor.maven:cfg-module (-)
980: remote -> org.quattor.pan:panc-maven-archetype (-)
981: remote -> org.rauschig:maven-archetype-bundle (A maven archetype that incorporates common artifacts for OSS develop
ment and OSGi compatibility)
982: remote -> org.resthub:resthub-jpa-backbonejs-archetype (-)
983: remote -> org.resthub:resthub-jpa-backbonejs-multi-archetype (-)
984: remote -> org.resthub:resthub-mongodb-backbonejs-archetype (-)
985: remote -> org.resthub:resthub-mongodb-backbonejs-multi-archetype (-)
986: remote -> org.rhq:rhq-plugin-archetype (-)
987: remote -> org.rhq.maven:smartgwt-war-archetype (archetype for a Maven project for a SmartGWT web application (WAR))

988: remote -> org.richfaces.archetypes:richfaces-archetype-kitchensink (A starter Java EE 6 webapp project for use on J
Boss AS 7 / EAP 6, generated from the
        jboss-javaee6-webapp archetype)
989: remote -> org.richfaces.archetypes:richfaces-archetype-simpleapp (-)
990: remote -> org.sadiframework:sadi-service-archetype (-)
991: remote -> org.scala-tools.archetypes:liftweb-archetype-blank (Archetype - blank project for liwftweb)
992: remote -> org.scala-tools.archetypes:liftweb-archetype-hellolift (Archetype - hellolift sample liwftweb application
)
993: remote -> org.scala-tools.archetypes:scala-archetype-simple (The maven-scala-plugin is used for compiling/testing/r
unning/documenting scala code in maven.)
994: remote -> org.scalatra.scalate.tooling:scalate-archetype-guice_2.10 (An archetype which creates an empty Scalate Gu
ice web application)
995: remote -> org.scalatra.scalate.tooling:scalate-archetype-guice_2.11 (An archetype which creates an empty Scalate Gu
ice web application)
996: remote -> org.scalatra.scalate.tooling:scalate-archetype-jersey_2.10 (An archetype which creates an empty Scalate w
eb application)
997: remote -> org.scalatra.scalate.tooling:scalate-archetype-jersey_2.11 (An archetype which creates an empty Scalate w
eb application)
998: remote -> org.scalatra.scalate.tooling:scalate-archetype-sitegen_2.10 (An archetype which creates an empty Scalate
static website generation project)
999: remote -> org.scalatra.scalate.tooling:scalate-archetype-sitegen_2.11 (An archetype which creates an empty Scalate
static website generation project)
1000: remote -> org.sculptorgenerator:sculptor-maven-archetype (Maven archetype for a business tier project using the Sc
ulptor code generator)
1001: remote -> org.sculptorgenerator:sculptor-maven-archetype-ear (Maven archetype for a EAR project using the Sculptor
 code generator)
1002: remote -> org.sculptorgenerator:sculptor-maven-archetype-parent (Maven archetype for a parent project using the Sc
ulptor code generator)
1003: remote -> org.sculptorgenerator:sculptor-maven-archetype-web (Maven archetype for a WAR project using the Sculptor
 code generator)
1004: remote -> org.siqisource.agave:archetypes-quickstart (-)
1005: remote -> org.sitoolkit.archetype:sit-archetype (This project is generated from org.sitoolkit.archetype:sit-archet
ype)
1006: remote -> org.sitoolkit.tester:sit-tester-archetype (archetype for sit-tester)
1007: remote -> org.slf4j:slf4j-archetype (The slf4j Archetype)
1008: remote -> org.slick2d:slick2d-basic-game-archetype (Maven archetype for a Slick2D based game)
1009: remote -> org.sonatype.flexmojos:flexmojos-archetypes-application (-)
1010: remote -> org.sonatype.flexmojos:flexmojos-archetypes-library (-)
1011: remote -> org.sonatype.flexmojos:flexmojos-archetypes-modular-webapp (-)
1012: remote -> org.sonatype.nexus.archetypes:nexus-plugin-archetype (-)
1013: remote -> org.springframework.boot:spring-boot-sample-actuator-archetype (Spring Boot Actuator Sample)
1014: remote -> org.springframework.boot:spring-boot-sample-actuator-log4j-archetype (Spring Boot Actuator Log4J Sample)

1015: remote -> org.springframework.boot:spring-boot-sample-actuator-noweb-archetype (Spring Boot Actuator Non-Web Sampl
e)
1016: remote -> org.springframework.boot:spring-boot-sample-actuator-ui-archetype (Spring Boot Actuator UI Sample)
1017: remote -> org.springframework.boot:spring-boot-sample-amqp-archetype (Spring Boot AMQP Sample)
1018: remote -> org.springframework.boot:spring-boot-sample-aop-archetype (Spring Boot AOP Sample)
1019: remote -> org.springframework.boot:spring-boot-sample-batch-archetype (Spring Boot Batch Sample)
1020: remote -> org.springframework.boot:spring-boot-sample-data-jpa-archetype (Spring Boot Data JPA Sample)
1021: remote -> org.springframework.boot:spring-boot-sample-data-mongodb-archetype (Spring Boot Data MongoDB Sample)
1022: remote -> org.springframework.boot:spring-boot-sample-data-redis-archetype (Spring Boot Data Redis Sample)
1023: remote -> org.springframework.boot:spring-boot-sample-data-rest-archetype (Spring Boot Data REST Sample)
1024: remote -> org.springframework.boot:spring-boot-sample-integration-archetype (Spring Boot Integration Sample)
1025: remote -> org.springframework.boot:spring-boot-sample-jetty-archetype (Spring Boot Jetty Sample)
1026: remote -> org.springframework.boot:spring-boot-sample-profile-archetype (Spring Boot Profile Sample)
1027: remote -> org.springframework.boot:spring-boot-sample-secure-archetype (Spring Boot Security Sample)
1028: remote -> org.springframework.boot:spring-boot-sample-servlet-archetype (Spring Boot Servlet Sample)
1029: remote -> org.springframework.boot:spring-boot-sample-simple-archetype (Spring Boot Simple Sample)
1030: remote -> org.springframework.boot:spring-boot-sample-tomcat-archetype (Spring Boot Tomcat Sample)
1031: remote -> org.springframework.boot:spring-boot-sample-traditional-archetype (Spring Boot Traditional Sample)
1032: remote -> org.springframework.boot:spring-boot-sample-web-jsp-archetype (Spring Boot Web JSP Sample)
1033: remote -> org.springframework.boot:spring-boot-sample-web-method-security-archetype (Spring Boot Web Method Securi
ty Sample)
1034: remote -> org.springframework.boot:spring-boot-sample-web-secure-archetype (Spring Boot Web Secure Sample)
1035: remote -> org.springframework.boot:spring-boot-sample-web-static-archetype (Spring Boot Web Static Sample)
1036: remote -> org.springframework.boot:spring-boot-sample-web-ui-archetype (Spring Boot Web UI Sample)
1037: remote -> org.springframework.boot:spring-boot-sample-websocket-archetype (Spring Boot WebSocket Sample)
1038: remote -> org.springframework.boot:spring-boot-sample-xml-archetype (Spring Boot XML Sample)
1039: remote -> org.springframework.osgi:spring-osgi-bundle-archetype (Spring OSGi Maven2 Archetype)
1040: remote -> org.springframework.ws:spring-ws-archetype (Spring Web Services Maven2 Archetype.)
1041: remote -> org.sqlproc:sqlproc-archetype-simple-jdbc (SQL Processor Archetype for Simple JDBC Application)
1042: remote -> org.sqlproc:sqlproc-archetype-simple-spring (SQL Processor Archetype for Simple Spring Application)
1043: remote -> org.structr:structr-base-archetype (Structr is an open source framework based on the popular Neo4j graph
 database.)
1044: remote -> org.structr:structr-simple-example-archetype (Structr is an open source framework based on the popular N
eo4j graph database.)
1045: remote -> org.structr:structr-ui-archetype (Structr is an open source framework based on the popular Neo4j graph d
atabase.)
1046: remote -> org.sweble.wikitext:swc-example-basic-archetype (An archetype that creates a simple application which is
 able to parse a page
    written in Wikitext and render it as HTML.)
1047: remote -> org.sweble.wikitext:swc-example-serialization-archetype (An example project that contains a simple appli
cation that is able to parse
    a page written in Wikitext and serialize it to XML, JSON or binary.)
1048: remote -> org.sweble.wikitext:swc-example-xpath-archetype (An archetype that creates a simple application which is
 able to parse
    a page written in Wikitext and perform an XPath query on that document.)
1049: remote -> org.switchyard.archetypes:switchyard-application (-)
1050: remote -> org.syncope:syncope-archetype (Syncope archetype)
1051: remote -> org.telosys.starterkits:angularHtml5offline-starterkit (archetype for starter Kit angular Html5 offline)

1052: remote -> org.telosys.starterkits:struts-jpa-starterkit (archetype for starter Kit Struts)
1053: remote -> org.tinygroup:buproject (-)
1054: remote -> org.tinygroup:flowcomponent (-)
1055: remote -> org.tinygroup:org.tinygroup.flowcomponentarchetype (-)
1056: remote -> org.tinygroup:org.tinygroup.plugincomponentarchetype (-)
1057: remote -> org.tinygroup:org.tinygroup.uicomponentarchetype (-)
1058: remote -> org.tinygroup:plugincomponent (-)
1059: remote -> org.tinygroup:servicecomponentarchetype (-)
1060: remote -> org.tinygroup:uicomponent-archetype (-)
1061: remote -> org.tinygroup:webappproject (-)
1062: remote -> org.trailsframework:trails-archetype (-)
1063: remote -> org.trailsframework:trails-secure-archetype (-)
1064: remote -> org.tynamo:tynamo-archetype (-)
1065: remote -> org.uberfire:uberfire-component-archetype (UberFire Component Archetype)
1066: remote -> org.uberfire:uberfire-project-archetype (UberFire Project Archetype)
1067: remote -> org.wicketstuff.scala:wicket-scala-archetype (-)
1068: remote -> org.wicketstuff.scala:wicketstuff-scala-archetype (Basic setup for a project that combines Scala and Wic
ket,
                depending on the Wicket-Scala project. Includes an example Specs
                test.)
1069: remote -> org.wikbook:wikbook.archetype (-)
1070: remote -> org.wildfly.archetypes:wildfly-subsystem (An archetype that generates a skeleton project for implementin
g a WildFly 8 subsystem)
1071: remote -> org.wiperdog:wiperdog-osgi-bundle-archetype (-)
1072: remote -> org.wiperdog:wiperdog-osgi-ipojo-archetype (-)
1073: remote -> org.wisdom-framework:wisdom-default-project-archetype (-)
1074: remote -> org.wisdom-framework:wisdom-simple-watcher-archetype (-)
1075: remote -> org.xaloon.archetype:xaloon-archetype-wicket-jpa-glassfish (-)
1076: remote -> org.xaloon.archetype:xaloon-archetype-wicket-jpa-spring (-)
1077: remote -> org.xwiki.commons:xwiki-commons-component-archetype (Make it easy to create a maven project for creating
 XWiki Components.)
1078: remote -> org.xwiki.rendering:xwiki-rendering-archetype-macro (Make it easy to create a maven project for creating
 XWiki Rendering Macros.)
1079: remote -> org.zkoss:zk-archetype-component (An archetype that generates a starter ZK component project)
1080: remote -> org.zkoss:zk-archetype-extension (An archetype that generates a starter ZK extension project)
1081: remote -> org.zkoss:zk-archetype-theme (An archetype that generates a starter ZK theme project)
1082: remote -> org.zkoss:zk-archetype-webapp (An archetype that generates a starter ZK CE webapp project)
1083: remote -> org.zkoss:zk-ee-eval-archetype-webapp (An archetype that generates a starter ZK EE-eval webapp project)
1084: remote -> org.zkoss:zk-ee-eval-archetype-webapp-spring (An archetype that generates a starter ZK EE-eval webapp pr
oject with Spring)
1085: remote -> org.zkoss:zk-ee-eval-archetype-webapp-spring-jpa (An archetype that generates a starter ZK EE-eval webap
p project with Spring and JPA)
1086: remote -> pl.bristleback:webapp-archetype (Web archetype for Bristleback Websocket Framework)
1087: remote -> pro.savant.circumflex:webapp-archetype (-)
1088: remote -> ru.circumflex:circumflex-archetype (-)
1089: remote -> ru.nikitav.android.archetypes:release (-)
1090: remote -> ru.nikitav.android.archetypes:release-robolectric (-)
1091: remote -> ru.stqa.selenium:webdriver-java-archetype (Archetype for a Maven project intended to develop tests with
Selenium WebDriver and JUnit/TestNG)
1092: remote -> ru.stqa.selenium:webdriver-junit-archetype (Archetype for a Maven project intended to develop tests with
 Selenium WebDriver and JUnit)
1093: remote -> ru.stqa.selenium:webdriver-testng-archetype (Archetype for a Maven project intended to develop tests wit
h Selenium WebDriver and TestNG)
1094: remote -> se.vgregion.javg.maven.archetypes:javg-minimal-archetype (-)
1095: remote -> sk.seges.sesam:sesam-annotation-archetype (-)
1096: remote -> tk.skuro:clojure-maven-archetype (A simple Maven archetype for Clojure)
1097: remote -> tr.com.lucidcode:kite-archetype (A Maven Archetype that allows users to create a Fresh Kite project)
1098: remote -> uk.ac.rdg.resc:edal-ncwms-based-webapp (-)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 439:
Choose org.apache.maven.archetypes:maven-archetype-quickstart version:
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1
Choose a number: 6:
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.1/maven-arche
type-quickstart-1.1.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.1/maven-archet
ype-quickstart-1.1.jar (7 KB at 1.2 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.1/maven-arche
type-quickstart-1.1.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.1/maven-archet
ype-quickstart-1.1.pom (2 KB at 3.3 KB/sec)
Define value for property 'groupId': : yuki.maven.app
Define value for property 'artifactId': : module
Define value for property 'version':  1.0-SNAPSHOT: : 0.0.1-SNAPSHOT
Define value for property 'package':  yuki.maven.app: :
Confirm properties configuration:
groupId: yuki.maven.app
artifactId: module
version: 0.0.1-SNAPSHOT
package: yuki.maven.app
 Y: : y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: D:\Maven
[INFO] Parameter: package, Value: yuki.maven.app
[INFO] Parameter: groupId, Value: yuki.maven.app
[INFO] Parameter: artifactId, Value: module
[INFO] Parameter: packageName, Value: yuki.maven.app
[INFO] Parameter: version, Value: 0.0.1-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: D:\Maven\module
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 09:44 min
[INFO] Finished at: 2014-09-02T19:59:33+08:00
[INFO] Final Memory: 11M/29M
[INFO] ------------------------------------------------------------------------
D:\Maven>

打开D:\Maven\module\pom.xml,把junit的version改为4.10 ,删除刚刚新建的模块module
执行 :mvn archetype:generate  -DgroupId=yuki.maven.app2.module1  -DartifactId=module2  -Dversion=0.0.1-SNAPSHOT

然后默认选择版本,选择yes后新建项目

4.eclipse配置maven
这是在客户端创建,怎样在eclipse里面创建
Eclipse Kepler中已经有自带的maven
Preferences>Maven>Installations>Add
选择安装的maven根目录D:\Idea\config\apache-maven-3.2.3
Preferences>Maven>User Settings>Browse
选择D:\Idea\config\apache-maven-3.2.3\conf\settings.xml

5.新建maven项目
File>New>Other>Maven>Maven Project>Next>Next
有大量的ArtifactId,这里选择maven-archetype-quickstart
Next>填写GroupId、ArtifactId、Version、Package
可以看到新建的maven项目

约定优于配置
新建Source Folder>src/main/resources,存放配置文件
新建Source Folder>test/main/resources,存放测试配置文件

三、新建Maven项目
1.通过pom.xml文件引入Hibernate的jar包
新建实体类yuki.maven.user.core.model.User,为User创建构造方法:无参构造,没有id的构造
/user-core/src/main/java/yuki/maven/user/core/model/User.java

package yuki.maven.user.core.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="T_USER")
public class User
{
    private int id;
    private String username;
    private String password;
    private String nickname;

    public User() {
    }
    public User(String username, String password, String nickname) {
        super();
        this.username = username;
        this.password = password;
        this.nickname = nickname;
    }

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

}

pom.xml中junit的版本号改为4.10

访问http://mvnrepository.com/ 搜索hibernate
点击Core Hibernate O/RM Functionality,4.3.6.Final
复制maven选项卡中的xml文本到dependencies标签下
打开Console>MavenConsole,可以看到

14-9-2 GMT+0800下午10:41:54: [INFO] Downloaded http://repo.maven.apache.org/maven2/org/hibernate/hibernate-core/4.3.6.Final/hibernate-core-4.3.6.Final.jar
14-9-2 GMT+0800下午10:41:58: [INFO] Using 'UTF-8' encoding to copy filtered resources.
14-9-2 GMT+0800下午10:41:58: [INFO] Copying 0 resource
14-9-2 GMT+0800下午10:41:58: [INFO] Using 'UTF-8' encoding to copy filtered resources.
14-9-2 GMT+0800下午10:41:58: [INFO] Copying 0 resource
14-9-2 GMT+0800下午10:41:59: [INFO] Using 'UTF-8' encoding to copy filtered resources.
14-9-2 GMT+0800下午10:41:59: [INFO] Copying 0 resource
14-9-2 GMT+0800下午10:41:59: [INFO] Using 'UTF-8' encoding to copy filtered resources.
14-9-2 GMT+0800下午10:41:59: [INFO] Copying 0 resource

这说明Maven已下载了hibernate的依赖包,可以看到文件:
D:\Idea\maven\repository\org\hibernate\hibernate-core\4.3.6.Final\hibernate-core-4.3.6.Final.jar
打开Maven Dependencies,在下面可以看到已引入的Hibernate的包

2.配置eclipse的代码提示
自动代码提示:
preference>Keys>搜索content>ContentAssist=Alt+/
preference>Java>Editor>ContentAssist/AutoActivation
把javadoc中的@ 剪切到Java中
在编辑器中输入@ 就会自动给出提示的下拉列表


在User类中加入注解

3.引入oracle的驱动jar包
http://mvnrepository.com/artifact/com.oracle/ojdbc14/10.2.0.4.0
在pom.xml上粘贴以来后,显示报错
打开D:\Idea\maven\repository\com\oracle\ojdbc14\10.2.0.4.0
发现没有对应的jar包,是因为访问地址404错误
http://central.maven.org/maven2/com/oracle/ojdbc14/10.2.0.4.0/ojdbc14-10.2.0.4.0.jar


访问http://www.java2s.com/Code/Jar/o/ojdbc14.htm 下载ojdbc14-10.2.0.4.0.jar

在目录下执行驱动jar所在路径下执行:

mvn install:install-file -DgroupId=com.oracle  -DartifactId=ojdbc14 -Dversion=10.2.0.4.0 -Dpackagin

pom.xml文件不再报错
在项目中引入log4j

4.配置文件
引入dtd文件hibernate-configuration-3.0.dtd,参照dtd的<!DOCTYPE>
Public ID的Key上填写:-//Hibernate/Hibernate Configuration DTD 3.0//EN
Alternative web address:http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd
通过这个约束在src/main/resources下新建配置文件hibernate.cfg.xml
/hibernate-release-4.3.6.Final/documentation/manual/en-US/html_single/index.html
参照配置文件进行配置hibernate

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">kongdy</property>
        <property name="connection.password">yuki</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml" /> -->
        <mapping class="yuki.maven.user.core.model.User" />
    </session-factory>
</hibernate-configuration>

配置log4j.properties文件

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %p %c{1} %L -%m%n
log4j.rootlogger=warm,stdout
log4j.logger.org.hibernate.SQL=debug

5.新建用户访问类
按照帮助文档中的Startup and helpers新建HibernateUtil类

/user-core/src/main/java/yuki/maven/user/core/util/HibernateUtil.java

package yuki.maven.user.core.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            return configuration.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

新建UserDao并测试TestUserDao,
/user-core/src/main/java/yuki/maven/user/core/dao/IUserDao.java

package yuki.maven.user.core.dao;

import yuki.maven.user.core.model.User;

public interface IUserDao {

    void add(User user);
    User loadByUsername(String username);
}

/user-core/src/main/java/yuki/maven/user/core/dao/UserDao.java

package yuki.maven.user.core.dao;

import org.hibernate.Session;

import yuki.maven.user.core.model.User;
import yuki.maven.user.core.util.HibernateUtil;

public class UserDao implements IUserDao {

    public void add(User user) {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            session.save(user);

            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.getSessionFactory().close();
        }
    }

    public User loadByUsername(String username) {
        Session session = null;
        User user = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

//            user = (User) session.createQuery("from User where username=?").setParameter(0, username).uniqueResult();
            user = (User) session.createQuery("from User where username=?").setParameter(0, username).list().get(0);

            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.getSessionFactory().close();
        }
        return user;
    }

}

/user-core/src/test/java/yuki/maven/user/core/dao/UserDaoTest.java

package yuki.maven.user.core.dao;

import org.junit.After;
import org.junit.Before;
//import org.junit.Test;

import yuki.maven.user.core.model.User;

public class UserDaoTest {

    private UserDao userDao;

    @Before
    public void setUp() throws Exception {
//        Class.forName("yuki.maven.user.core.util.HibernateUtil");
        userDao = new UserDao();
        System.out.println("开始测试");
    }

//    @Test
    public void testAdd() {
        userDao.add(new User("username1", "password1", "用户名1"));
    }

//    @Test
    public void testLoadByUsername() {
        User user = userDao.loadByUsername("username1");
        System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getNickname());
    }

    @After
    public void tearDown() {
        userDao = null;
        System.out.println("测试结束");
    }

}

6.测试用户访问类
pom.xml右键>Run As>Maven build…
Main>Goals=clean test>Apply>Run


JRE>Installed JREs…>选择JDK的路径而不是JRE的路径
Apply>Run,再次运行后就可以直接点击[Alt+Shift+X,M]的那个了

运行时会报错
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
http://www.journaldev.com/2897/solved-hibernateexception-access-to-dialectresolutioninfo-cannot-be-null-when-hibernate-dialect-not-set
运行services.msc,打开服务OracleServiceXE,OracleXETNSListener

必须一个一个测试,否则报出异常
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]

四、新建其它的maven模块
1.新建模块user-log
pom.xml按下Ctrl+Shift+F就会自动排版
http://mvnrepository.com/artifact/commons-logging/commons-logging/1.2
http://mvnrepository.com/artifact/log4j/log4j/1.2.17
对两个模块打包:user-core>Run As>clean package,user-log>Run As>clean package

/user-log/src/main/java/yuki/maven/user/log/Log.java

package yuki.maven.user.log;

public class Log
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

新建user-service模块,添加日志的依赖

2.隐藏变量
${basedir} 项目根目录
${project.build.directory} 构建目录,缺省为target
${project.build.outputDirectory} 构建过程输出目录,缺省为target/classes
${project.build.finalName} 产出物名称,缺省为${project.artifactId}-${project.version}
${project.packaging} 打包类型,缺省为jar
${project.xxx} 当前pom文件的任意节点的内容

     <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>user-core</artifactId>
            <!-- <version>${project.version}</version> -->
        </dependency>

Missing artifact yuki.maven.app1-user:maven-core:jar:0.0.1-SNAPSHOT
本地仓库找不到,对user-core和user-log执行install命令
再引入user-core和user-log的依赖时,对应它们的依赖也被依赖进来,被称为依赖传递
利用引入的内容完成用户服务类

3.依赖范围
这时,用户的访问类可能还在做开发,这里用到了easymock
http://mvnrepository.com/artifact/org.easymock/easymock/3.2

/user-service/src/main/java/yuki/maven/user/service/IUserService.java

package yuki.maven.user.service;

import yuki.maven.user.core.model.User;

public interface IUserService
{
    void add(User user);
    User loadByUsername(String username);
}

/user-service/src/main/java/yuki/maven/user/service/UserService.java

package yuki.maven.user.service;

import yuki.maven.user.core.dao.IUserDao;
import yuki.maven.user.core.model.User;

public class UserService implements IUserService {

    private IUserDao userDao;
    public UserService(IUserDao userDao) {
        this.userDao = userDao;
    }

    public void add(User user) {
        userDao.add(user);
    }

    public User loadByUsername(String username) {
        return userDao.loadByUsername(username);
    }

}

/user-service/src/test/java/yuki/maven/user/service/UserServiceTest.java

package yuki.maven.user.service;

import static org.junit.Assert.*;
import static org.easymock.EasyMock.*;

import org.hibernate.cfg.CreateKeySecondPass;
import org.hibernate.internal.util.compare.EqualsHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import yuki.maven.user.core.dao.IUserDao;
import yuki.maven.user.core.model.User;

public class UserServiceTest {

    private IUserDao userDao;
    private IUserService userService;
    private User user;

    @Before
    public void setUp() throws Exception {
        userDao = createStrictMock(IUserDao.class);
        userService = new UserService(userDao);
        user = new User();
    }

    @After
    public void tearDown() throws Exception {
        verify(userDao);
    }

    @Test
    public void testAdd() {
        userDao.add(user);
        expectLastCall();
        replay(userDao);
        userService.add(user);

    }

    @Test
    public void testLoadByUsername() {
        expect(userDao.loadByUsername("admin")).andReturn(user);
        replay(userDao);
        User user2 = userService.loadByUsername("admin");
        System.out.println(EqualsHelper.equals(user2, user));
    }

}

依赖范围的取值scope,什么时候把依赖加进去
compile:编译、打包,默认的依赖范围
provided:编译、测试,比如servlet-api不会打包进去
runtime:编译时不依赖,测试和运行时依赖,比如数据库驱动jar
test:仅仅在测试的时候依赖,比如junit
只有放在/src/test文件夹下的java文件才能使用junit

被依赖模块的scope=test的jar不会传递给依赖它的模块
被传递过来的依赖也被称为是间接依赖

在dependency hierarchy中可以看到依赖的继承关系
如果依赖级别相同,会依赖写在前面的依赖
如果依赖级别不同,就会先依赖层次最浅的

可以通过dependency的子标签exclusions排除不需要继承的依赖

     <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>user-log</artifactId>
            <!-- <version>${project.version}</version> -->
            <!-- <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions> -->
        </dependency>

这里可以解决jar包冲突问题

4.聚合
可以在三个模块的根目录中创建一个pom.xml文件
通过它可以集中编译项目,这个pom.xml可以什么都不用写
在eclipse中,new maven project
选择create a simple project(skip archetype selection)
ArtifactId = user-aggregate,packaging = pom > Finish

打开pom.xml文件在project标签下填写modules标签

/user-aggregate/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>yuki.maven.app1-user</groupId>
    <artifactId>user-aggregate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>../user-core</module>
        <module>../user-log</module>
        <module>../user-service</module>
    </modules>
</project>

这样,对这个文件执行maven命令就是向包含的module执行maven命令

5.继承
配置里面很多是重复的,有可能也会设置大量的常量,这些在项目里都是重复的
可以让所有的项目继承一个根类,所有的项目继承这个类
新建user-parent项目,选择create a simple project,packaging=pom

复制相同的内容到user-parent/pom.xml中,
添加parent标签,同时删掉复制的内容,
相对路径relativePath=../user-parent/pom.xml
这时,会提示原先写的groupIdheversion有重复,可以删掉它们

依赖也是可以继承的,但是这意味着每一个项目都要加进被继承的依赖
把user-core中的dependencies标签加在dependencyManagement中
这样,就可以删掉user-core依赖的版本、排除信息了

\user-parent\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>yuki.maven.app1-user</groupId>
    <artifactId>user-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <url>http://maven.apache.org</url>

    <modules>
        <module>../user-core</module>
        <module>../user-log</module>
        <module>../user-service</module>
    </modules>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <!-- <version>3.8.1</version> -->
                <version>4.10</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.3.6.Final</version>
            </dependency>
            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc14</artifactId>
                <version>10.2.0.4.0</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>user-core</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>user-log</artifactId>
                <version>${project.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

/user-core/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>

    <parent>
        <groupId>yuki.maven.app1-user</groupId>
        <artifactId>user-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../user-parent/pom.xml</relativePath>
    </parent>

    <!-- <groupId>yuki.maven.app1-user</groupId> -->
    <artifactId>user-core</artifactId>
    <!-- <version>0.0.1-SNAPSHOT</version> -->
    <packaging>jar</packaging>

    <name>user-core</name>
    <!-- <url>http://maven.apache.org</url>

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

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>
    </dependencies>

</project>

/user-log/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>

    <parent>
        <groupId>yuki.maven.app1-user</groupId>
        <artifactId>user-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../user-parent/pom.xml</relativePath>
    </parent>

    <artifactId>user-log</artifactId>
    <packaging>jar</packaging>

    <name>user-log</name>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>
    </dependencies>
</project>

/user-service/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>

    <parent>
        <groupId>yuki.maven.app1-user</groupId>
        <artifactId>user-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../user-parent/pom.xml</relativePath>
    </parent>

    <!-- <groupId>yuki.maven.app1-user</groupId> -->
    <artifactId>user-service</artifactId>
    <!-- <version>0.0.1-SNAPSHOT</version> -->
    <packaging>jar</packaging>

    <name>user-service</name>
    <url>http://maven.apache.org</url>

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

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <!-- <version>4.10</version> -->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>user-core</artifactId>
            <!-- <version>${project.version}</version> -->
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>user-log</artifactId>
            <!-- <version>${project.version}</version> -->
            <!-- <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions> -->
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

可以把聚合文件modules也放在user-parent中
如果把user-parent/pom.xml放在所有模块的根目录下,就需要删除路径的../
对应的模块继承的../user-parent/pom.xml也可以改成pom.xml
继承的是绝对路径是pom.xml文件,聚合是模块的位置

五、其它
1.文件路径
pom.xml
src
  |-main
    |-java
      |-package
    |-resources
  |-test
    |-java
      |-package
    |-resources
target
  |-classes

2.版本
大版本的变化.分支的变化.更新-里程碑
SNAPSHOT:快照版本,正在开发中
alpha:内部测试版本
beta:使用者使用测试
Release(RC):释放版本
GeneralAvailable(GA):正常可用的版本

本文的目录结构:

本文参考了 [孔浩_MAVEN_项目管理及自动构建工具] 的视频课程

更多好文请关注:http://www.cnblogs.com/kodoyang/

kongdongyang

2014/9/6

项目管理及自动构建工具Maven的更多相关文章

  1. 项目管理构建工具——Maven(基础篇)

    项目管理构建工具--Maven(基础篇) 在前面的内容中我们学习了JDBC并且接触到了jar包概念 在后面我们的实际开发中会接触到很多jar包,jar包的导入需要到互联网上进行就会导致操作繁琐 Mav ...

  2. 项目管理构建工具——Maven(高阶篇)

    项目管理构建工具--Maven(高阶篇) 我们在之前的文章中已经基本了解了Maven,但也仅仅只止步于了解 Maven作为我们项目管理构建的常用工具,具备许多功能,在这篇文章中我们来仔细介绍 分模块开 ...

  3. 着重基础之—构建工具—Maven的依赖管理

    着重基础之—构建工具—Maven的依赖管理 项目构建利器Maven给我们开发人员带来了极大的便利,从繁琐的jar包管理中脱身的程序员终于可以有时间再进入另一个坑了. 我今天要给大家分享的内容是我在实际 ...

  4. Java项目工程化之项目构建工具Maven

    欢迎查看Java开发之上帝之眼系列教程,如果您正在为Java后端庞大的体系所困扰,如果您正在为各种繁出不穷的技术和各种框架所迷茫,那么本系列文章将带您窥探Java庞大的体系.本系列教程希望您能站在上帝 ...

  5. 关于node.js和npm,cnpm的安装记录以及gulp自动构建工具的使用

    关于node.js和npm,cnpm的安装记录以及gulp自动构建工具的使用   工作环境:window下 在一切的最开始,安装node.js (中文站,更新比较慢http://nodejs.cn/) ...

  6. 构建工具maven

     构建工具maven  =UTF-8''Gradle Effective Implementation Guide.pdf: http://www.t00y.com/file/76854506 b ...

  7. 自动构建工具Gulp

    摘要:  gulp与grunt一样,都是自动构建工具.和grunt相比它更突出一个流的概念,任务是一个接一个执行的.今天就分享如何用gulp做自动化. 安装: gulp也是基于node环境,所以安装g ...

  8. 跨平台自动构建工具v1.0.2 发布

    XMake是一个跨平台自动构建工具,支持在各种主流平台上构建项目,类似cmake.automake.premake,但是更加的方便易用,工程描述语法更简洁直观,支持平台更多,并且集创建.配置.编译.打 ...

  9. 项目自动构建工具对比(Maven、Gradle、Ant)

    Java世界中主要有三大构建工具:Ant.Maven和Gradle.经过几年的发展,Ant几乎销声匿迹.Maven也日薄西山,而Gradle的发展则如日中天. Maven的主要功能主要分为5点,分别是 ...

随机推荐

  1. Java中使用验证码和二维码

    资源 需要:   jelly-core-1.7.0.GA.jar 网站:   http://lychie.github.io/products.html 将下载下来的 jelly-core-1.7.0 ...

  2. Partitioner

    partitioner 是map中的数据映射到不同的reduce时的根据.一般情况下,partitioner会根据数据的key来把数据平均分配给不同的reduce,同时保证相同的key分发到同一个re ...

  3. USACO Section 3.2: Sweet Butter

    这题我自己是用邻接矩阵+dijskstra方法来求的,第九个例子TLE.网上看了别人的代码,是用邻接表+BFS来完成. 这里可以学到两个小技巧,邻接表的表示方法和INT_MAX的表示方法. /* ID ...

  4. Node 实现 AES 加密,结果输出为“byte”。

    Node 实现 AES 加密,结果输出为"byte". 最近做个需求,对接一个平台的接口,该平台采用 AES (Advanced Encryption Standard)加密算法, ...

  5. Delphi遍历文件夹

    /// <remarks> /// 遍历文件夹 (引用SysUtils单元) /// </remarks> procedure TfrmMusicMenu.SearchInDi ...

  6. iPhone —— 如何自制铃声(图文)

    iPhone不像其他手机可以直接将MP3格式的文件设为铃声.但如果想用自己喜欢的歌曲作为铃声该怎么办呢?请听我一一道来. 一.将MP3文件转换成iPhone铃声能识别的M4R格式文件 1.向iTune ...

  7. java-基础练习题3

    [程序3] 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身.例如:153是一个"水仙花数",因 ...

  8. res里面的drawable(ldpi、mdpi、hdpi、xhdpi、xxhdpi)

    (1)drawable-hdpi里面存放高分辨率的图片,如WVGA (480x800),FWVGA (480x854) (2)drawable-mdpi里面存放中等分辨率的图片,如HVGA (320x ...

  9. poj 3694 pku 3694 Network tarjan求割边 lca

    题意:给你一个连通图,然后再给你n个询问,每个询问给一个点u,v表示加上u,v之后又多少个桥.一个最容易想到的办法就是先加边找桥,加边找桥,这样可定超时.那么就可以缩点,因为如果一条边不是桥那么无论怎 ...

  10. [xUnix 开发环境--01] MAMP mac os 10.10 配置经历、要点——01. phpmyadmin连不上

    Mac OS 10.10已经自带了apache2和php(php的路径我至今还没不知道,太懒没去找) 用brew安装mysql, 在官网上下载了phpmyadmin,按官方方式配置完后,登录不上,也不 ...