您的位置:首页 > 其它

Maven学习总结:几个常用的maven插件

2017-01-25 21:28 507 查看


简介

    我们使用maven做一些日常的工作开发的时候,无非是想利用这个工具带来的一些便利。比如它带来的依赖管理,方便我们打包和部署运行。这里几个常见的插件就是和这些工程中常用的步骤相关。

 


maven-compile-plugin

    这个插件就如同名字所显示的这样,用来编译源代码的。最开始碰到这个插件是在于有的时候我们下载了一些工程需要编译的时候,比如我们输入命令:mvn install ,但是系统编译的时候报错了,错误的信息如下:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project springJMS: Compilation failure: Compilation failure:
[ERROR] /home/frank/programcode/SpringJMSSample/src/main/java/huangbowen/net/jms/MessageSender.java:[6,1] error: annotations are not supported in -source 1.3
[ERROR]
[ERROR] (use -source 5 or higher to enable annotations)
[ERROR] /home/frank/programcode/SpringJMSSample/src/main/java/net/EmbedBrokerApp.java:[5,7] error: static import declarations are not supported in -source 1.3
[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 从错误显示的信息我们就可以看出,这是因为编译的时候是默认用的javac 1.3版本的,太老了不支持代码里的特性。为了修改这个问题,我们需要设置编译器的版本。解决这个问题的办法也比较简单,就是直接在后面的插件部分增加如下的插件,比如如下部分,将编译器的版本设定为1.6:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>


exec-maven-plugin

    我们写一些java console相关的程序时,比较头疼的一点就是真正要通过命令行将打包后的程序执行起来还是比较麻烦的。我们需要在命令行里敲如下的命令:java -cp ***.jar:**.jar:/**/ 。因为要将classpath目录以及引用的类库都加入进来,并指定运行的入口,这样子每次用手工的方式来处理实在是太繁琐也比较容易出错。所以一种办法就是利用这个插件,通过一些基本的配置,我们可以执行起代码来的时候很方便。一个典型的配置如下:

 <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.yunzero.App</mainClass>
</configuration>
</plugin>

如果我们运行的时候需要提供一些输入的参数,也可以通过configuration的元素里添加。这样后续要执行这个程序时,我们只需要在命令行执行如下命令:mvn exec:java ,然后程序就可以运行起来了。

 


maven-dependency-plugin

 

  还有一个比较常用的插件就是这个。我们在IDE的环境里编译和执行代码的时候,那是直接引用一些类库。但是在我们实际部署的环境里,那边很可能就一个java执行环境,不可能有源代码和IDE。这个时候,我们需要将源代码编译打包。这个时候的一个问题就是如果我们引用的库很多的话,我们希望能够把他们统一打包到一个目录下,比如lib文件夹。这样部署执行的时候只需要将编译生成的程序jar包和依赖包文件夹拷到特定目录去执行。要实现这个效果也比较容易:
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
从前面的配置里我们可以看到,插件的执行被配置到install这个阶段。这样,当我们执行命令:mvn clean install 的时候,会发现对应的target目录里生成了对应的jar包和依赖包。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  maven