1、Hello项目的pom.xml文件
<?xml version="1.0" ?>
<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>com.victor.maven</groupId>
<artifactId>Hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Hello</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2、Hello项目源码
import org.junit.Test;
import static junit.framework.Assert.*;
public class Hello {
public String sayHello(String name){
return "Hello "+name+"!";
}
}
public class HelloTest {
@Test
public void testHello(){
Hello hello = new Hello();
String results = hello.sayHello("litingwei");
assertEquals("Hello litingwei!",results);
}
}
3、HelloFriend项目的pom.xml文件
<?xml version="1.0" ?>
<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>com.victor.maven</groupId>
<artifactId>HelloFriend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HelloFriend</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.victor.maven</groupId>
<artifactId>Hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
4、HelloFriend项目主程序
import com.victor.maven.Hello;
public class HelloFriend {
public String sayHelloToFriend(String name){
Hello hello = new Hello();
String str = hello.sayHello(name)+" I am "+this.getMyName();
System.out.println(str);
return str;
}
public String getMyName(){
return "John";
}
}
5、HelloFriend项目测试程序
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
import com.victor.maven.Hello;
public class HelloFriendTest {
@Test
public void testHelloFriend(){
HelloFriend helloFriend = new HelloFriend();
String results = helloFriend.sayHelloToFriend("litingwei");
assertEquals("Hello litingwei! I am John",results);
}
}
6、Maven Jar包依赖总结
关键是对Hello的依赖
这里Hello就是我们的第一个Maven工程,现在HelloFriend对它有依赖。那么这个依赖能否成功呢?更进一步的问题是:HelloFriend工程会到哪里去找Hello呢?
答案是:本地仓库。任何一个Maven工程会根据坐标到本地仓库中去查找它所依赖的jar包。如果能够找到则可以正常工作,否则就不行。