Eclipse新建maven项目, ivy+ant项目或gradle项目

来源:互联网 发布:android 网络框架 编辑:程序博客网 时间:2024/04/29 12:38

Copyright 2016 by 蔡舒啸 保持署名-非商业性使用-相同方式共享 Creative Commons BY-NC-ND 3.0


目录

  • 一 Eclipse新建Maven项目
    • 第0步 下载maven
    • 第1步 添加maven全球仓库的的国内镜像
    • 可选 设置maven代理
    • 可选 配置本地仓库
      • i 先设置你的本地仓库
      • ii 从第三方包的官网下载第三方jar包 并通过maven install安装到maven本地仓库
      • 例子一 - 单文件 jar 安装到本地仓库
    • 第3步 pomxml添加maven-compiler-plugin插件
    • 第4步 pomxml添加依赖的第三方包 以junit4为例
    • 第5步 根据pomxml更新项目 自动下载依赖包
    • maven编译打包时忽略测试类
    • maven编译打包时添加非resources目录下的配置文件
  • 二 ant_ivy方案
    • 第0步 下载和配置
    • 第1步 使用ivy
    • ant脚本常用方法
      • move替代老版本的rename
  • 三 gradle方案
  • 后记


我的环境:
Ubuntu 16.04 64bit
Eclipse Neon for J2EE
JDK 8
Maven 3.3.9

待验证:
maven不能链接源码是硬伤?http://my.oschina.net/enyo/blog/369843
gradle的灵活性远超maven,大规模集群布署也是支持的
是吗?我在的两个公司都在用了
build.xml的编写规则太难,gradle里很多潜规则

注意:公司没有Maven私服的话,别用 Maven 。它的官网服务器在国外,国内唯一镜像 OSChina 还不稳定,更新也不及时。

搭建 maven 私服是你在国内使用 maven/gradle/ivy 的第一步!
搭建 maven 私服是你在国内使用 maven/gradle/ivy 的第一步!
搭建 maven 私服是你在国内使用 maven/gradle/ivy 的第一步!

一 Eclipse新建Maven项目

第0步 下载maven

Eclipse贴心地自带了Maven,但是这份好意心领了就行

不使用Eclipse自带的maven的原因有:
1 eclipse for j2EE自带maven3, 但是正如前文提到的, maven3依赖jdk7, 而很多服务器还是jdk6. 所以必须对JDK 6兼容, 即需要使用maven2.2.1版本
2 安装自己下载的 jar 包到 maven 本地仓库,与项目无关,最好在命令行里完成。命令行是不能使用 eclipse 自带的maven的,因为你压根就找不到自带的 maven 的安装目录
3 熟悉命令行的 mvn 在你远程 ssh 登录到服务器上编译你的项目时很有用

搜索apache maven, 进入官网, 找到download
下载完成后, 解压到任意目录, 如 ~/maven3.3.9/ (下文中称为${M2_HOME})

第1步 添加maven全球仓库的的国内镜像

因为国情, 从maven的全球仓库下载经常链接不上. 所以添加国内镜像对正常使用maven而言是必须的一步.
以OSChina镜像为例

引用小写K@cnblogs:
修改 maven 配置文件
1. 全局配置文件路径 ${M2_HOME}/conf/settings.xml
2. 当前用户配置文件路径 /home/当前用户/.m2/settings.xml
3. 当前用户配置覆盖全局配置

打开 ${M2_HOME}/conf/settings.xml

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">  <mirrors>    <mirror>      <id>CN</id>      <name>OSChina Central</name>      <url>http://maven.oschina.net/content/groups/public/</url>      <mirrorOf>central</mirrorOf>    </mirror>  </mirrors></settings> 

可选 设置maven代理

很多公司链接外网需要用代理 , 如果在公司想用maven, 必须设置代理.

引用小写K@cnblogs:
修改 maven 配置文件
1. 全局配置文件路径 ${M2_HOME}/conf/settings.xml
2. 当前用户配置文件路径 /home/当前用户/.m2/settings.xml
3. 当前用户配置覆盖全局配置

打开 ${M2_HOME}/conf/settings.xml 添加如下内容:

 <settings 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/settings-1.0.0.xsd">     <localRepository />     <interactiveMode />     <usePluginRegistry />     <offline />     <pluginGroups />     <servers />     <proxies>         <!-- 使用代理上网 -->         <proxy>             <id>optional</id>             <active>true</active>             <protocol>http</protocol>             <username></username>             <password></password>             <host>172.16.1.35</host>             <port>80</port>             <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>         </proxy>     </proxies>     <profiles />     <activeProfiles /> </settings> 

然而有时候代理也没用,因为maven仓库里根本没有你要的包. 这种情况下,
需要自行下载你要的包, 然后使用maven install把包安装到你的maven本地仓库.

可选 配置本地仓库

(i) 先设置你的本地仓库:

引用小写K@cnblogs:
修改 maven 配置文件
1. 全局配置文件路径 ${M2_HOME}/conf/settings.xml
2. 当前用户配置文件路径 /home/当前用户/.m2/settings.xml
3. 当前用户配置覆盖全局配置

<settings>      <localRepository>D:\maven_new_repository</localRepository>  </settings> 

(ii) 从第三方包的官网下载第三方jar包, 并通过maven install安装到maven本地仓库.

添加 jar 包到 maven 本地仓库的操作如下:
1. 建立一个新的文件夹,将jar文件存放在该文件夹下。文件夹下最好只存放该文件。
2. (可选,建议)同目录下新建 pom.xml 文件,配置包版本信息。
3. 在cmd窗口中执行以下命令安装到本地库:

mvn install:install-file -Dfile=your-artifact-1.0.jar \                         [-DpomFile=your-pom.xml] \                         [-Dsources=src.jar] \                         [-Djavadoc=apidocs.jar] \                         [-DgroupId=org.some.group] \                         [-DartifactId=your-artifact] \                         [-Dversion=1.0] \                         [-Dpackaging=jar] \                         [-Dclassifier=sources] \                         [-DgeneratePom=true] \                         [-DcreateChecksum=true]

例子一 - 单文件 jar 安装到本地仓库

自行下载有 jar 包 /home/foo/postgresql9.4.1208.jar
推荐使用同目录下 /home/foo/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>org.postgresql</groupId>  <artifactId>postgresql</artifactId>  <version>9.4.1208</version>  <packaging>jar</packaging></project>

终端里执行命令:

mvn install:install-file \          -Dfile=your-artifact-1.0.jar \          -DpomFile=your-pom.xml```                         [-DgroupId=org.some.group] \                         [-DartifactId=your-artifact] \                         [-Dversion=1.0] \                         [-DgroupId=org.some.group] \                         [-DartifactId=your-artifact] \                         [-Dversion=1.0] \屏幕提示如下: [INFO] Scanning for projects...[INFO] Searching repository for plugin with prefix: 'install'.[INFO] ------------------------------------------------------------------------[INFO] Building Maven Default Project[INFO]    task-segment: [install:install-file] (aggregator-style)[INFO] ------------------------------------------------------------------------[INFO] [install:install-file {execution: default-cli}][INFO] Installing /home/foo/postgresql-9.4.1208.jar to /home/foo/.m2/repository/org/postgresql/postgresql/9.4.1208/postgresql-9.4.1208.jar[INFO] Installing /home/foo/pom.xml to /home/foo/.m2/repository/org/postgresql/postgresql/9.4.1208/postgresql-9.4.1208.pom[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESSFUL[INFO] ------------------------------------------------------------------------[INFO] Total time: < 1 second[INFO] Finished at: Thu Jun 30 00:05:52 CST 2016[INFO] Final Memory: 5M/150M[INFO] ------------------------------------------------------------------------这样,即使 Maven 官方仓库没有的包,我们也可以通过本地仓库下载到项目中。使用时,只要把**/home/foo/pom.xml** 的内容复制到项目的 **pom.xml** 中,如:<div class="se-preview-section-delimiter"></div>

第3步 pom.xml添加maven-compiler-plugin插件

compiler插件能解决:
1:maven 2.1默认用jdk 1.3来编译,maven 3 貌似是用jdk 1.5,如果项目用的jdk 1.6也会有问题,compiler插件可以指定JDK版本为1.6。

    <build>        <plugins>            <!--插件都位于build标签的plugins标签下-->            <plugin>                <artifactId>maven-compiler-plugin</artifactId>                <version>2.3.2</version>                <configuration>                    <source>1.6</source>                    <target>1.6</target>                </configuration>            </plugin>        </plugins>    </build>

第4步 pom.xml添加依赖的第三方包, 以junit4为例

添加前, 可以在官网http://mvnrepository.com/查询仓库是否有你需要的包

    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.11</version>            <scope>test</scope>        </dependency>    </dependencies>

右键项目名, Maven -> Update Project
就会自动下载junit4.11.jar和断言包hamcrest-core-1.3.jar
要maven自动执行单元测试, 还需要添加surefire-junit4 2.4.3插件

    <build>        <plugins>            <!--插件都位于build标签的plugins标签下-->            <plugin>                <groupId>org.apache.maven.surefire</groupId>                <artifactId>surefire-junit4</artifactId>                <version>2.4.3</version>                <configuration>                    <skip>false</skip>                    <testFailureIgnore>true</testFailureIgnore>                </configuration>            </plugin>        </plugins>    </build>

Maven官方维护了两个插件列表:
GroupId:=org.apache.maven.plugins,这里的插件最为成熟
GroupId:=org.codehaus.mojo,这里的插件没有那么核心。
更多maven插件介绍请移步这篇文章.

这步可能发生如下错误:

Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin:2.3.2:testCompile (execution: default-testCompile, phase: test-compile)

第5步 根据pom.xml更新项目, 自动下载依赖包

右键项目, 选Maven –> Update Project…, 如下图
这里写图片描述
这样, pom.xml中的dependency和plugin就会下载到本地, 并添加到项目的WEB-INF/lib目录

特别地,当安装本地 jar 包到本地 maven 仓库后, 需要更新 pom.xml 才能正确识别本地 maven 仓库的 jar 包.
右键项目, 选Maven –> Update Project…

maven编译打包时忽略测试类

maven命令时可以携带虚拟机参数:-dmaven.test.skip=true。如果是eclipse执行maven命令,可以配置该命令:Run as->Run Configurations->勾上Skip Tests

maven编译打包时添加”非resources目录下”的配置文件

maven默认会把src/main/resources下的所有配置文件以及src/main/java下的所有java文件打包或发布到target\classes下面,但是现实我们可能会在src/main/java下面也放置一些配置文件如hibernate配置文件或mybatis mapper配置文件等,如果不做一些额外配置,那我们打包后的项目可能找不到这些必须的资源文件,因此在pom.xml中增加类似如下配置:

<build>  <resources>   <resource>    <directory>src/main/java</directory>    <includes>     <include>**/*.xml</include>    </includes>   </resource>  </resources> </build>

就会将src/main/java下的xml文件随同java编译后的class文件一同copy到相应的class目录

二 ant_ivy方案

程序员甲: 项目用的ant+ivy, ivy也是用的maven仓库. 为什么不用maven?
程序员乙: 问初代目去啊
初代目: 那是一个1999年的夏天…十年后本来想转maven的, 但是发现还有ivy, 果断用了

转自"Ant权威指南":

1998年,有一位程序员改变了整个Java世界。James Duncan Davisdson在试图使用当时的构建工具(GNU Make、批处理文件和shell脚本)来创建一个跨平台的Tomcat构建时,做了多种努力均不能成功。因此,他在从欧洲飞回美国的途中设计出了自己的构建实用工具,并为命名为Ant,因这是一个小东西,但却能做大事。James为了解决自己的问题(即创建一个跨平台的构建)而提出的这种快速而简单的解决方案已经演变成Java环境中应用最为广泛的构建管理工具。

转自CSDN论坛:

ant就是實現批處理功能,它把你想要做的多個任務通過xml文件方式描述出來,然後你可以通過ant +targetName來執行這項任務,主要是為了我們經常重復做某些事提供方便,比如從事開發工作,你會經常更新文件,編譯文件,測試運行你的程序,如果你一步一步操作就會感覺比較慢了,不如使用ant方便了

第0步 下载和配置

ivy2.4(Dec, 2014) + ant 1.9.6(Jun, 2015)
ivy可以理解为ant的一个插件, 使用maven2的仓库提供第三方包的下载.
两个都下载完后, 把ivy-2.4.0.jar 直接放到ant1.9.6根目录下的lib.

用来下载ivy的build.xml, 用ant跑一下就下载了.

<?xml version="1.0" encoding="GBK"?><project name="go-ivy" default="go" xmlns:ivy="antlib:org.apache.ivy.ant">    <!-- the version of ivy -->    <property name="ivy.install.version" value="2.4.0" />    <property name="ivy.jar.dir" value="${basedir}/ivy" />    <!-- the download path of ivy -->    <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" />    <property name="build.dir" value="build" />    <property name="src.dir" value="src" />    <target name="download-ivy" unless="skip.download">        <mkdir dir="${ivy.jar.dir}"/>        <!-- download Ivy from web site -->        <echo message="installing ivy..."/>        <get src="http://repo1.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar"             dest="${ivy.jar.file}" usetimestamp="true"/>    </target>    <!-- =================================          target: install-ivy            this target is not necessary if you put ivy.jar in your ant lib directory            if you already have ivy in your ant lib, you can simply remove this            target and the dependency the 'go' target has on it         ================================= -->    <target name="install-ivy" depends="download-ivy" description="--> install ivy">        <!-- try to load ivy here from local ivy dir, in case the user has not already dropped              it into ant's lib dir (note that the latter copy will always take precedence).              We will not fail as long as local lib dir exists (it may be empty) and              ivy is in at least one of ant's lib dir or the local lib dir. -->        <path id="ivy.lib.path">            <fileset dir="${ivy.jar.dir}" includes="*.jar"/>        </path>        <taskdef resource="org/apache/ivy/ant/antlib.xml"                  uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>    </target>        <!-- =================================          target: go                    Go ivy, go!         ================================= -->    <target name="go" depends="install-ivy, generate-src"            description="--> resolve dependencies, compile and run the project">        <echo message="using ivy to resolve commons-lang 2.1..."/>        <!-- here comes the magic line: asks ivy to resolve a dependency on             commons-lang 2.1 and to build an ant path with it from its cache  -->        <ivy:cachepath organisation="commons-lang" module="commons-lang" revision="2.1"                       pathid="lib.path.id" inline="true"/>        <echo message="compiling..."/>        <mkdir dir="${build.dir}" />        <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="lib.path.id" />        <echo>We are now ready to execute our simple program with its dependency on commons-lang.Let's go!        </echo>        <java classname="example.Hello">            <classpath>                <path refid="lib.path.id" />                <path location="${build.dir}" />            </classpath>        </java>    </target>    <!-- =================================          target: generate-src            'Generates' the class source. It actually just echo a simple java            source code to a file. In real life this file would already be            present on your file system, and this target wouldn't be necessary.         ================================= -->    <target name="generate-src">        <mkdir dir="${src.dir}/example" />        <echo file="${src.dir}/example/Hello.java">package example;import org.apache.commons.lang.WordUtils;public class Hello {    public static void main(String[] args) {        String  message = "hello ivy !";        System.out.println("standard message : " + message);        System.out.println("capitalized by " + WordUtils.class.getName()                                + " : " + WordUtils.capitalizeFully(message));    }}        </echo>    </target>    <!-- =================================          target: clean         ================================= -->    <target name="clean" description="--> clean the project">        <delete includeemptydirs="true" quiet="true">            <fileset dir="${src.dir}" />            <fileset dir="${build.dir}" />        </delete>    </target>    <!-- =================================          target: clean-ivy         ================================= -->    <target name="clean-ivy" description="--> clean the ivy installation">        <delete dir="${ivy.jar.dir}"/>    </target>    <!-- =================================          target: clean-cache         ================================= -->    <target name="clean-cache" depends="install-ivy"            description="--> clean the ivy cache">        <ivy:cleancache />    </target></project>

第1步 使用ivy

这部分内容转自http://www.micmiu.com/software/build/apache-ivy-start/

项目名  |--build.properties     |--build.xml  `--ivy.xml--src    --example            Hello.java

build.properties:

############################################## 项目信息##############################################区分项目的唯一 IDproject.id=xxx# 应用名称(简写,例如myapp),默认为project.id,请开发人员修改project.name=xxx#子系统名称subject.name=pagi_eri# 项目简要描述project.discription=企业信用风险识别项目#项目启动年份project.inception.year=2015#业务系列,例如:产险、寿险、证券、银行、等project.series=新渠道# 项目运行应用服务器环境,开发人员不需要修改project.appserver=tomcat#版本,开发人员根据版本管理员要求修改,正式版本根据本配置发布#项目有改动时候需要升级版本project.revision=1.43.0#项目邮件接收人员,测试体系日编译,正式发布的结果会发送到#该邮件列表所有人,邮箱地址用逗号分割开project.mail.list=wangchenyang774@pingan.com.cnproject.contact=wangchenyang774@pingan.com.cn#项目根目录project.base=../.############################################## 部署目录#############################################rel.dir=rel#发布目录publish.dir=${rel.dir}#publish.dir=${rel.dir}#部署描述文件存放目录deploy_desc.dir=${project.base}/deploy_desc#部署流水线属性文件deployflow.properties=${project.base}/deployflow.properties#发布 war 包目录publish.apps.dir=${publish.dir}/apps#publish.apps.dir=${publish.dir}/apps#发布 jar 包目录publish.libs.dir=${publish.dir}/lib#publish.libs.dir=${publish.dir}/libpublish.configs.dir=${publish.dir}/config# 在开发当中,可以把{deploy.exploded.dir}直接发布deploy.exploded.dir=${project.base}/dist/tomcat/${project.name}# WAR文件存放目录deploy.war.dir=${project.base}/dist/tomcatwar.file=${project.name}.war############################################## 第三方包管理############################################## 第三方包配置文件ivy.config.url=http://xxx/ivyconf.xml

build.xml 内容如下:

<project name="hello-ivy" default="run" xmlns:ivy="antlib:org.apache.ivy.ant">    <!-- some variables used -->    <property environment="env" />    <property name="prop.tmp" value="prop_tmp" />    <!--jdk自带的unicode转码工具-->    <native2ascii src="." dest="${prop.tmp}" includes="build.properties" />    <property file="${prop.tmp}/build.properties" />    <property name="lib.dir" value="lib" />    <property name="build.dir" value="build" />    <property name="src.dir" value="src" />    <!-- paths used for compilation and run  -->    <path id="lib.path.id">        <fileset dir="${lib.dir}" />    </path>    <path id="run.path.id">        <path refid="lib.path.id" />        <path location="${build.dir}" />    </path>    <!-- =================================          target: resolve         ================================= -->    <target name="resolve" description="--> retreive dependencies with ivy">        <ivy:retrieve/>    </target>        <!-- =================================          target: report         ================================= -->    <target name="report" depends="resolve" description="--> generates a report of dependencies">        <ivy:report todir="${build.dir}"/>    </target>    <!-- =================================          target: run         ================================= -->    <target name="run" depends="resolve" description="--> compile and run the project">        <mkdir dir="${build.dir}" />        <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="lib.path.id" includeAntRuntime="false"/>        <property name="msg" value="hello ivy !"/>        <java classpathref="run.path.id" classname="example.Hello">            <arg value="-message"/>            <arg value="${msg}"/>        </java>    </target>    <!-- =================================          target: clean         ================================= -->    <target name="clean" description="--> clean the project">        <delete includeemptydirs="true">            <fileset dir="${basedir}">                <exclude name="src/**" />                <exclude name="build.xml" />              <exclude name="ivy.xml" />            </fileset>        </delete>    </target>    <!-- =================================          target: clean-cache         ================================= -->    <target name="clean-cache" description="--> clean the ivy cache">        <ivy:cleancache />    </target></project>

ivy.xml 内容如下:

<ivy-module version="2.0">    <info organisation="org.apache" module="hello-ivy"/>    <dependencies>        <dependency org="commons-lang" name="commons-lang" rev="2.0"/>        <dependency org="commons-cli" name="commons-cli" rev="1.0"/>    </dependencies></ivy-module>

ant脚本常用方法

move(替代老版本的rename)

<move file="${dist}/${warDest}/WEB-INF/config/log4j.build.properties"   tofile="${dist}/${warDest}/WEB-INF/config/log4j.properties" />

三 gradle方案

- 为什么不用maven?
- 你知道开源界的GG潮流吗? GG = Github + Gradle, spring, hibernate等最著名的框架都在用

后记

Ant代表的是编程天才对开源运动的巨大影响力, 1998年James Duncan Davisdson在飞机上完成的Ant是跨平台自动化部署的开山鼻祖, ivy则让Ant这颗老树发了新芽, 因为太多项目使用了Ant, 所以Ant+ivy的组合也是一个Java开发人员必须掌握的;

maven代表的是有组织的开源运动的巅峰 - apache基金会, 顺便提一句, Ant最后也纳入了apache基金会.

gradle代表的是21世纪自由的开源社区越来越大的影响力, hibernate, spring两大框架对gradle的支持说明了问题

思考题:
Maven仓库对于Maven, 就好比__对于Java
A) JDK
B) JVM
C) Scala
D) Groovy

Ant的包依赖管理插件ivy和Gradle使用的Java第三方包仓库是__
A) Maven仓库
B) 他们各自的公共仓库
C) 不使用公共仓库, 需要配置私有仓库
D) 以上都不正确

0 0