一、概述
通過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路徑下;
再次運行,即正常;