一、概述
通过ant实现项目的自动化部署,jar包生成,替换,tomcat关停、启动,查看项目日志;
通过java程序调用已编辑好的ant脚本build.xml配置文件中指定的target;
文中文件路径均为作者自定义路径;读者可根据自己实际情况命名并做相应修改;只要实现目的即可;
二、环境
jdk版本:jdk1.8.0_161;
ant版本:apache-ant-1.10.5;
maven版本:apache-maven-3.5.2;
IDE:eclipse Luna Release (4.4.0);
三、环境变量配置
1、ANT_HOME;
2、CLASSPATH
3、JAVA_HOME;
4、Path;
5、MAVEN_HOME;
四、eclipse配置
1、Window-->Preferences-->Java-->Installed JREs-->Add
如下图所示:
2、添加JRE环境,如下图配置,
3、注意要将tools.jar包添加进JRE system libraries,(不然在程序调用ant脚本中打jar包的target时会报错)添加方法如下图:
五、调用ant脚本的java程序
1 import java.io.File; 2 3 import org.apache.tools.ant.BuildException; 4 import org.apache.tools.ant.DefaultLogger; 5 import org.apache.tools.ant.Project; 6 import org.apache.tools.ant.ProjectHelper; 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9 10 public class AntDemo {11 public static void main(String[] args) throws Exception {12 final Logger logger = LoggerFactory.getLogger(AntDemo.class);13 String localPath ="D:/devcode/workspace/dataSourceTest/src/main/resources/test-display/build.xml";14 File buildFile = new File(localPath.toString());15 Project project = new Project(); String targetName = "test";16 try {17 DefaultLogger consoleLogger = new DefaultLogger();18 consoleLogger.setErrorPrintStream(System.err);19 consoleLogger.setOutputPrintStream(System.out);20 consoleLogger.setMessageOutputLevel(Project.MSG_INFO);21 project.addBuildListener(consoleLogger);22 project.fireBuildStarted();23 project.init();24 ProjectHelper helper = ProjectHelper.getProjectHelper();25 helper.parse(project, buildFile);26 project.executeTarget(targetName);27 project.fireBuildFinished(null);28 } catch (BuildException e) {29 // 构建抛出异常30 project.fireBuildFinished(e); 31 logger.error("Ant执行异常," + e.toString());32 throw new Exception("Ant执行异常," + e.toString(), e);33 }34 }35 }
六、ant脚本-build.xml
1 23 4 5 7 8 96 10 17 1811 12 1413 15 16 19 25 26 27 28 29 3020 2321 2224 31 37 3832 34 36 39 43 44 45 4640 41 42 47 51 52 5348 49 50 54 58 5955 56 57
七、测试运行
七、常见报错
因为ant脚本中存在scp标签,用执行文件上传,下载;sshexec标签,用于执行连接服务器并执行Linux命令;
因此在执行程序过程中,调用target(download-jar)或(tomcat-stop)时,可能会报错;需要单独下载jsch-0.1.54.jar;并将其复制粘贴到D:\development\apache-ant-1.10.5\lib路径下;
常见报错一:
Cause: the class org.apache.tools.ant.taskdefs.optional.ssh.SSHExec was not found.
This looks like one of Ant's optional components.
Action: Check that the appropriate optional JAR exists in
-ANT_HOME\lib
-the IDE Ant configuration dialogs
Do not panic, this is a common problem.
The commonest cause is a missing JAR.
This is not a bug; it is a configuration problem
解决方案:
在程序代码上右键-->Run As-->Run Configurations...-->classpath--User Entries-->Add External JARs...
全选路径D:\development\apache-ant-1.10.5\lib 下的jar包;之所以全选是为了保险,避免缺失jar包;
点击打开即添加成功;注意要事先将jsch-0.1.54.jar包复制到apache-ant-1.10.5\lib路径下;
再次运行,即正常;