天天看点

Maven实战. 3.2编写主代码

<b>3.2编写主代码</b>

项目主代码和测试代码不同,项目的主代码会被打包到最终的构件中(如jar),而测试代码只在运行测试时用到,不会被打包。默认情况下,maven假设项目主代码位于src/main/java目录,我们遵循maven的约定,创建该目录,然后在该目录下创建文件com/juvenxu/mvnbook/helloworld/helloworld.java,其内容如代码清单3-2所示:代码清单3-2hello world的主代码

package com.juvenxu.mvnbook.helloworld;

public class helloworld

{

public string sayhello()

return "hello maven";

}

public static void main(string[] args)

system.out.print(

new helloworld().sayhello()

);

这是一个简单的java类,它有一个sayhello()方法,返回一个string。同时这个类还带有一个main方法,创建一个helloworld实例,调用sayhello()方法,并将结果输出到控制台。

关于该java代码有两点需要注意。首先,在绝大多数情况下,应该把项目主代码放到src/main/java/目录下(遵循maven的约定),而无须额外的配置,maven会自动搜寻该目录找到项目主代码。其次,该java类的包名是com.juvenxu.mvnbook.helloworld,这与之前在pom中定义的groupid和artifactid相吻合。一般来说,项目中java类的包都应该基于项目的groupid和artifactid,这样更加清晰,更加符合逻辑,也方便搜索构件或者java类。

代码编写完毕后,使用maven进行编译,在项目根目录下运行命令 mvn clean compile会得到如下输出:[info] scanning for projects…

[info]

------------------------------------------------------------------------

[info] building maven hello world project

[info]tasksegment: [clean, compile]

[info] [clean:clean {execution: defaultclean}]

[info] deleting directory d:\code\helloworld\target

[info] [resources:resources {execution:

defaultresources}]

[info] skip non existing resourcedirectory d:

\code\helloworld\src\main\resources

[info] [compiler:compile {execution: defaultcompile}]

[info] compiling 1 source file to d: \code\helloworld\target\classes

[info] build successful

[info] total time: 1 second

[info] finished at: fri oct 09 02:08:09 cst

2009

[info] final memory: 9m/16m

------------------------------------------------------------------------clean告诉maven清理输出目录target/,compile告诉maven编译项目主代码,从输出中看到maven首先执行了clean:clean任务,删除target/目录。默认情况下,maven构建的所有输出都在target/目录中;接着执行resources:resources任务(未定义项目资源,暂且略过);最后执行compiler:compile任务,将项目主代码编译至target/classes目录(编译好的类为com/juvenxu/mvnbook/helloworld/helloworld.class)。

上文提到的clean:clean、resources:resources和compiler:compile对应了一些maven插件及插件目标,比如clean:clean是clean插件的clean目标,compiler:compile是compiler插件的compile目标。后文会详细讲述maven插件及其编写方法。

至此,maven在没有任何额外的配置的情况下就执行了项目的清理和编译任务。接下来,编写一些单元测试代码并让maven执行自动化测试。