需求:以前面创建的demo和demo1为例,新建一个mavenProject工程,将demo和demo1作为mavenProject的两个模块(module),然后在demo1的方法中使用demo类中的方法。
1.将demo和demo1放置到mavenProject的根目录下,并在mavenProject的pom文件中添加模块
<!--聚合 -->
<modules>
<module>/demo</module>
<module>/demo1</module>
</modules>
2.在demo1的pom文件中添加对demo模块的依赖
<dependencies>
<!--使用Junit4(注解方式运行)-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.steven.maven</groupId><!--项目的包名-->
<artifactId>demo</artifactId><!--项目的模块名(项目名)-->
<version>1.0-SNAPSHOT</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>
3.在demo1的方法中使用demo类中的方法
//demo的HelloWorld中定义的hello方法
public class HelloWorld {
public String hello(){
return "hello world!";
}
}
public class Speak {
public String hi(){
return new HelloWorld().hello();
}
}
4.测试
public class SpeakTest {
@Test
public void testHi(){
Assert.assertEquals("hello world!",new Speak().hi());
}
}