---
title: "在Maven2插件中用Velocity对配置文件的集中管理"
author: "danlley"
date: "2007-08-06T16:55:52Z"
tags: []
categories: ["企业架构"]
slug: "maven2-velocity"
draft: false
lastmod: "2007-08-06T16:55:52Z"
id: 109451
url: "https://danlley.iteye.com/blog/109451"
---

正如我在“用Velocity进行配置文件信息的集中管理 ”————http://danlley.iteye.com/blog/106130 中的许诺，这个专题将专门说说如何在Maven2插件中用Velocity对配置文件的集中管理。有了上个专题的基础，我这里也就化繁就简了。下面这段代码是通过上个专题的例子进行改写、整理、重构以后的代码，核心任务就是处理配置文件。

 

java 代码

01. public class VelocitySamples{
02. private VelocityContext context;
03. /\**
04. * 
    
    comments : 程序入口
05. \*
06. * author  danlley
07. * coding date  2007-7-24
08. * @param path            资源文件路径，默认与Maven默认资源文件路径相同
09. * @param template        资源仓库
10. * @param destPath        目标路径，默认与Maven编译路径相同
11. * @throws Exception
12. \*/
13. public void dealFile(String path,String template,String destPath) throws Exception{
14. File\[] files=new File(path).listFiles();
15. String errMsg="请核对路径： "+path+" 确认是否有资源文件存在于此路径下.";
16. if(files.length==0)
17. throw new FileNotFoundException(errMsg);
18. context=new VelocityContext();
19. applyProperties(path+template);//initial the VelocityContext
20. Velocity.init();
21. for(File file:files){
22. if(!file.isFile())
23. continue;
24. String origName=file.getName();
25. if(!checkFile(origName))
26. continue;
27. createFile(origName,destPath,path);
28. }
29. }
30. /\**
31. * 
    
    comments : 此方法用于检查文件是否为待处理文件，在本例子中待处理文件的后缀均为“\*.danlley”
32. *               如：log4j配置文件则为log4j.xml.danlley，转换后为log4j.xml
33. \*
34. * author  danlley
35. * coding date  2007-8-6
36. * @param origName
37. * @return
38. * @throws Exception
39. \*/
40. public boolean checkFile(String origName)throws Exception{
41. int index=origName.lastIndexOf(".");
42. String tail=origName.substring(index+1,origName.length());
43. if("danlley".equals(tail))
44. return true;
45. else
46. return false;
47. }
48. /\**
49. * 
    
    comments : 生成转换后的文件
50. \*
51. * author  danlley
52. * coding date  2007-7-24
53. * @param origFileName
54. * @param destPath
55. * @param targetPath
56. * @throws Exception
57. \*/
58. public void createFile(String origFileName,String destPath,String targetPath) throws Exception{
59. int index=origFileName.lastIndexOf(".");
60. String destFileName=origFileName.substring(0,index);
61. BufferedWriter writer=new BufferedWriter(new FileWriter(destPath+destFileName));
62. Template template=Velocity.getTemplate(targetPath+origFileName);
63. template.merge(context,writer);
64. writer.flush();
65. writer.close();
66. }
67. /\**
68. * 
    
    comments : 为 VelocityContext 获取替换信息
69. \*
70. * author  danlley
71. * coding date  2007-7-24
72. * @param path
73. * @throws Exception
74. \*/
75. public void applyProperties(String path) throws Exception{
76. FileInputStream fis=new FileInputStream(path);
77. if(null==fis)throw new NullPointerException("broken file or bad file!");
78. Properties prop=new Properties();
79. prop.load(fis);
80. Enumeration enu=prop.keys();
81. while(enu.hasMoreElements()){
82. String key=enu.nextElement().toString();
83. String value=prop.get(key).toString();
84. context.put(key,value);
85. }
86. }
87. }

既然是Maven插件开发，那我这里也就用Maven来管理工程了，下面是POM的配置祥单：

xml 代码

01. &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
02. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4\_0\_0.xsd"&gt;
03. &lt;modelVersion&gt;4.0.0modelVersion&gt;
04. &lt;groupId&gt;org.danlleygroupId&gt;
05. &lt;artifactId&gt;maven-velocity-pluginartifactId&gt;
06. &lt;packaging&gt;maven-pluginpackaging&gt;
07. &lt;version&gt;1.0version&gt;
08. &lt;name&gt;maven-velocity-pluginname&gt;
09. &lt;url&gt;http://maven.apache.orgurl&gt;
10. &lt;build&gt;
11. &lt;plugins&gt;
12. &lt;plugin&gt;
13. &lt;groupId&gt;org.apache.maven.pluginsgroupId&gt;
14. &lt;artifactId&gt;maven-compiler-pluginartifactId&gt;
15. &lt;configuration&gt;
16. &lt;source&gt;1.5source&gt;
17. &lt;target&gt;1.5target&gt;
18. configuration&gt;
19. plugin&gt;
20. plugins&gt;
21. build&gt;
22. &lt;dependencies&gt;
23. &lt;dependency&gt;
24. &lt;groupId&gt;junitgroupId&gt;
25. &lt;artifactId&gt;junitartifactId&gt;
26. &lt;version&gt;4.0version&gt;
27. &lt;scope&gt;testscope&gt;
28. dependency&gt;
29. &lt;dependency&gt;
30. &lt;groupId&gt;velocitygroupId&gt;
31. &lt;artifactId&gt;velocityartifactId&gt;
32. &lt;version&gt;1.4version&gt;
33. dependency&gt;
34. &lt;dependency&gt;
35. &lt;groupId&gt;org.apache.mavengroupId&gt;
36. &lt;artifactId&gt;maven-plugin-apiartifactId&gt;
37. &lt;version&gt;2.0version&gt;
38. dependency&gt;
39. dependencies&gt;
40. project&gt;

让我不解的是Maven在进行代码编译时采用的还是Older Pattern，但是我的代码又用到了一些JDK5的某些特性，万般无赖，我只好用下面的方式进行显式申明了：

xml 代码

1. &lt;plugin&gt;
2. &lt;groupId&gt;org.apache.maven.pluginsgroupId&gt;
3. &lt;artifactId&gt;maven-compiler-pluginartifactId&gt;
4. &lt;configuration&gt;
5. &lt;source&gt;1.5source&gt;
6. &lt;target&gt;1.5target&gt;
7. configuration&gt;
8. plugin&gt;

还需要强调的一点是下面这段代码，我这里没有用jar也没有用war，因为我写的不是资源包，而是插件：

xml 代码

1. &lt;packaging&gt;maven-pluginpackaging&gt;

接下来在src/main/scripts路径下定义文件velocity.mojos.xml。内容如下：

xml 代码

1. &lt;pluginMetadata&gt;
2. &lt;mojos&gt;
3. &lt;mojo&gt;
4. &lt;goal&gt;velocitygoal&gt;
5. &lt;call&gt;velocitycall&gt;
6. &lt;description&gt;Say Hello, World.description&gt;
7. mojo&gt;
8. mojos&gt;
9. pluginMetadata&gt;

Maven 官方的说明中好像说mojo的文件命名必须与goal一致，因此，由于我的goal是velocity，那mojo也就成了velocity.mojos.xml。当然至于这个goal到最后回去call什么东西，其实这里并不是很重要了，只要在使用plugin的工程中声明你需要call什么东西就可以了。如果大家对Maven插件开发比较感兴趣，可以到[http://danlley.iteye.com/blog/102159](http://danlley.iteye.com/blog/102159)去看看我的另外一片专题文章，希望对大家能够有所帮助。有了这篇文章做基础，我下面也就省去部分Maven相关的概念，直接给出我实现的钩子程序了（需要说明的一点是，在下面的这段程序中，注释和代码同样重要）。

java 代码

01. package org.danlley.util.samples;
02. import java.io.File;
03. import org.apache.maven.plugin.AbstractMojo;
04. import org.apache.maven.plugin.MojoExecutionException;
05. /\**
06. * replace.
07. \*
08. * @goal replace
09. \*/
10. public class VelocityMojo extends AbstractMojo {
11. /\**
12. * scriptSourceDirectory.
13. \*
14. * @parameter default-value="${project.build.scriptSourceDirectory}"
15. \*/
16. private String scriptSourceDirectory;
17. /\**
18. * outputDirectory.
19. \*
20. * @parameter default-value="${project.build.outputDirectory}"
21. \*/
22. private String outputDirectory;
23. /\**
24. * template.
25. \*
26. * @parameter default-value="${project.build.outputDirectory}"
27. \*/
28. private String template;
29. public void execute() throws MojoExecutionException {
30. try {
31. getLog().info("+-----------------------------------------+");
32. getLog().info("|             Velocity Files:             |");
33. getLog().info("+-----------------------------------------+");
34. listFile();
35. VelocitySamples \_instance = new VelocitySamples();
36. \_instance.dealFile(scriptSourceDirectory + "/", template, outputDirectory + "/");
37. getLog().info("生成文件已经被放置在路径："+outputDirectory+" 请核对！");
38. } catch (Exception e) {
39. e.printStackTrace();
40. }
41. }
42. /\**
43. * 
    
    comments : 只会列出需要处理的文件
44. \*
45. * author  danlley
46. * coding date  2007-8-6
47. * @throws Exception
48. \*/
49. public void listFile() throws Exception {
50. File\[] files = (new File(scriptSourceDirectory)).listFiles();
51. for (File file : files) {
52. VelocitySamples ve = new VelocitySamples();
53. if (ve.checkFile(file.getName())) {
54. getLog().info(file.getName());
55. }
56. }
57. }
58. }

接下来进行install，接受到 BUILD SUCCESSFUL消息意味着插件开发过程结束，下面说说使用。在需要使用该插件的Maven2工程中打开POM，加入如下代码：

xml 代码

01. &lt;build&gt;
02. &lt;plugins&gt;
03. &lt;plugin&gt;
04. &lt;groupId&gt;org.danlleygroupId&gt;
05. &lt;artifactId&gt;maven-velocity-pluginartifactId&gt;
06. &lt;version&gt;1.0version&gt;
07. &lt;configuration&gt;
08. &lt;template&gt;sample\_data.propertiestemplate&gt;
09. configuration&gt;
10. &lt;executions&gt;
11. &lt;execution&gt;
12. &lt;phase&gt;compilephase&gt;
13. &lt;goals&gt;
14. &lt;goal&gt;replacegoal&gt;
15. goals&gt;
16. execution&gt;
17. executions&gt;
18. plugin&gt;
19. plugins&gt;
20. build&gt;

 

 

加入工程以后我的测试执行结果如下：

F:\\workspaces\\maven-velocity-lab&gt;mvn compile  
\[INFO] Scanning for projects...  
\[INFO] -------------------------------------------------------------------------  
\---  
\[INFO] Building maven-velocity-lab  
\[INFO]    task-segment: \[compile]  
\[INFO] -------------------------------------------------------------------------  
\---  
\[INFO] \[resources:resources]  
\[INFO] Using default encoding to copy filtered resources.  
\[INFO] \[compiler:compile]  
\[INFO] Nothing to compile - all classes are up to date  
\[INFO] \[velocity:replace {execution: default}]  
\[INFO] +-----------------------------------------+  
\[INFO] |             Velocity Files:             |  
\[INFO] +-----------------------------------------+  
\[INFO] dlmchibernate.cfg.xml.danlley  
\[INFO] log4j.xml.danlley  
\[INFO] dlhibernate.cfg.xml.danlley  
\[INFO] download\_config.xml.danlley  
\[INFO] 生成文件已经被放置在路径：F:\\workspaces\\maven-velocity-lab\\target\\classes  
 请核对！  
\[INFO] ------------------------------------------------------------------------  
\[INFO] BUILD SUCCESSFUL  
\[INFO] ------------------------------------------------------------------------  
\[INFO] Total time: 1 second  
\[INFO] Finished at: Mon Aug 06 16:38:58 CST 2007  
\[INFO] Final Memory: 5M/9M  
\[INFO] ------------------------------------------------------------------------

 

**参考资料：**[http://maven.apache.org/guides/plugin/guide-java-plugin-development.html](http://maven.apache.org/guides/plugin/guide-java-plugin-development.html)