一、概述
通过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 importjava.io.File;2
3 importorg.apache.tools.ant.BuildException;4 importorg.apache.tools.ant.DefaultLogger;5 importorg.apache.tools.ant.Project;6 importorg.apache.tools.ant.ProjectHelper;7 importorg.slf4j.Logger;8 importorg.slf4j.LoggerFactory;9
10 public classAntDemo {11 public static void main(String[] args) throwsException {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 = newFile(localPath.toString());15 Project project = newProject();
String targetName = "test";16 try{17 DefaultLogger consoleLogger = newDefaultLogger();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 <?xml version="1.0" encoding="UTF-8"?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
34
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
七、测试运行
七、常见报错
因为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路径下;
再次运行,即正常;