`

在Maven2插件中用Velocity对配置文件的集中管理

阅读更多

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

 

java 代码
  1. public class VelocitySamples{   
  2.     private VelocityContext context;   
  3.   
  4.     /**  
  5.      * 

    comments : 程序入口

     
  6.      *          

     

     
  7.      * author  danlley  
  8.      * coding date  2007-7-24  
  9.      * @param path            资源文件路径,默认与Maven默认资源文件路径相同  
  10.      * @param template        资源仓库  
  11.      * @param destPath        目标路径,默认与Maven编译路径相同  
  12.      * @throws Exception  
  13.      */  
  14.     public void dealFile(String path,String template,String destPath) throws Exception{   
  15.         File[] files=new File(path).listFiles();   
  16.         String errMsg="请核对路径: "+path+" 确认是否有资源文件存在于此路径下.";   
  17.         if(files.length==0)   
  18.             throw new FileNotFoundException(errMsg);   
  19.         context=new VelocityContext();   
  20.         applyProperties(path+template);//initial the VelocityContext   
  21.         Velocity.init();   
  22.         for(File file:files){   
  23.             if(!file.isFile())   
  24.                 continue;   
  25.             String origName=file.getName();   
  26.             if(!checkFile(origName))   
  27.                 continue;   
  28.             createFile(origName,destPath,path);   
  29.         }   
  30.     }   
  31.        
  32.     /**  
  33.      * 

    comments : 此方法用于检查文件是否为待处理文件,在本例子中待处理文件的后缀均为“*.danlley”

     
  34.      *               如:log4j配置文件则为log4j.xml.danlley,转换后为log4j.xml  
  35.      *          

     

     
  36.      * author  danlley  
  37.      * coding date  2007-8-6  
  38.      * @param origName  
  39.      * @return  
  40.      * @throws Exception  
  41.      */  
  42.     public boolean checkFile(String origName)throws Exception{   
  43.         int index=origName.lastIndexOf(".");   
  44.         String tail=origName.substring(index+1,origName.length());   
  45.         if("danlley".equals(tail))   
  46.             return true;   
  47.         else  
  48.             return false;   
  49.     }   
  50.   
  51.     /**  
  52.      * 

    comments : 生成转换后的文件

     
  53.      *          

     

     
  54.      * author  danlley  
  55.      * coding date  2007-7-24  
  56.      * @param origFileName  
  57.      * @param destPath  
  58.      * @param targetPath  
  59.      * @throws Exception  
  60.      */  
  61.     public void createFile(String origFileName,String destPath,String targetPath) throws Exception{   
  62.         int index=origFileName.lastIndexOf(".");   
  63.         String destFileName=origFileName.substring(0,index);   
  64.         BufferedWriter writer=new BufferedWriter(new FileWriter(destPath+destFileName));   
  65.         Template template=Velocity.getTemplate(targetPath+origFileName);   
  66.         template.merge(context,writer);   
  67.         writer.flush();   
  68.         writer.close();   
  69.     }   
  70.   
  71.     /**  
  72.      * 

    comments : 为 VelocityContext 获取替换信息

     
  73.      *          

     

     
  74.      * author  danlley  
  75.      * coding date  2007-7-24  
  76.      * @param path  
  77.      * @throws Exception  
  78.      */  
  79.     public void applyProperties(String path) throws Exception{   
  80.         FileInputStream fis=new FileInputStream(path);   
  81.         if(null==fis)throw new NullPointerException("broken file or bad file!");   
  82.         Properties prop=new Properties();   
  83.         prop.load(fis);   
  84.         Enumeration enu=prop.keys();   
  85.         while(enu.hasMoreElements()){   
  86.             String key=enu.nextElement().toString();   
  87.             String value=prop.get(key).toString();   
  88.             context.put(key,value);   
  89.         }   
  90.     }   
  91. }  

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

xml 代码
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0modelVersion>  
  4.     <groupId>org.danlleygroupId>  
  5.     <artifactId>maven-velocity-pluginartifactId>  
  6.     <packaging>maven-pluginpackaging>  
  7.     <version>1.0version>  
  8.     <name>maven-velocity-pluginname>  
  9.     <url>http://maven.apache.orgurl>  
  10.     <build>  
  11.         <plugins>  
  12.             <!---->  
  13.             <plugin>  
  14.                 <groupId>org.apache.maven.pluginsgroupId>  
  15.                 <artifactId>maven-compiler-pluginartifactId>  
  16.                 <configuration>  
  17.                     <source>1.5source>  
  18.                     <target>1.5target>  
  19.                 configuration>  
  20.             plugin>  
  21.         plugins>  
  22.     build>  
  23.     <dependencies>  
  24.         <dependency>  
  25.             <groupId>junitgroupId>  
  26.             <artifactId>junitartifactId>  
  27.             <version>4.0version>  
  28.             <scope>testscope>  
  29.         dependency>  
  30.         <dependency>  
  31.             <groupId>velocitygroupId>  
  32.             <artifactId>velocityartifactId>  
  33.             <version>1.4version>  
  34.         dependency>  
  35.         <dependency>  
  36.             <groupId>org.apache.mavengroupId>  
  37.             <artifactId>maven-plugin-apiartifactId>  
  38.             <version>2.0version>  
  39.         dependency>  
  40.     dependencies>  
  41. project>  

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

xml 代码
  1. <!---->  
  2. <plugin>  
  3.     <groupId>org.apache.maven.pluginsgroupId>  
  4.     <artifactId>maven-compiler-pluginartifactId>  
  5.     <configuration>  
  6.         <source>1.5source>  
  7.         <target>1.5target>  
  8.     configuration>  
  9. plugin>  

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

xml 代码
  1. <packaging>maven-pluginpackaging>  

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

xml 代码
  1. <pluginMetadata>  
  2.     <mojos>  
  3.         <mojo>  
  4.             <goal>velocitygoal>  
  5.             <call>velocitycall>  
  6.             <description>Say Hello, World.description>  
  7.         mojo>  
  8.     mojos>  
  9. pluginMetadata>  

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

java 代码
  1. package org.danlley.util.samples;   
  2.   
  3. import java.io.File;   
  4.   
  5. import org.apache.maven.plugin.AbstractMojo;   
  6. import org.apache.maven.plugin.MojoExecutionException;   
  7.   
  8. /**  
  9.  * replace.  
  10.  *   
  11.  * @goal replace  
  12.  */  
  13. public class VelocityMojo extends AbstractMojo {   
  14.     /**  
  15.      * scriptSourceDirectory.  
  16.      *   
  17.      * @parameter default-value="${project.build.scriptSourceDirectory}"  
  18.      */  
  19.     private String scriptSourceDirectory;   
  20.     /**  
  21.      * outputDirectory.  
  22.      *   
  23.      * @parameter default-value="${project.build.outputDirectory}"  
  24.      */  
  25.     private String outputDirectory;   
  26.     /**  
  27.      * template.  
  28.      *   
  29.      * @parameter default-value="${project.build.outputDirectory}"  
  30.      */  
  31.     private String template;   
  32.   
  33.     public void execute() throws MojoExecutionException {   
  34.         try {   
  35.             getLog().info("+-----------------------------------------+");   
  36.             getLog().info("|             Velocity Files:             |");   
  37.             getLog().info("+-----------------------------------------+");   
  38.             listFile();   
  39.             VelocitySamples _instance = new VelocitySamples();   
  40.             _instance.dealFile(scriptSourceDirectory + "/", template, outputDirectory + "/");   
  41.             getLog().info("生成文件已经被放置在路径:"+outputDirectory+" 请核对!");   
  42.         } catch (Exception e) {   
  43.             e.printStackTrace();   
  44.         }   
  45.     }   
  46.        
  47.     /**  
  48.      * 

    comments : 只会列出需要处理的文件

     
  49.      *          

     

     
  50.      * author  danlley  
  51.      * coding date  2007-8-6  
  52.      * @throws Exception  
  53.      */  
  54.     public void listFile() throws Exception {   
  55.         File[] files = (new File(scriptSourceDirectory)).listFiles();   
  56.         for (File file : files) {   
  57.             VelocitySamples ve = new VelocitySamples();   
  58.             if (ve.checkFile(file.getName())) {   
  59.                 getLog().info(file.getName());   
  60.             }   
  61.         }   
  62.     }   
  63. }  

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

xml 代码
  1. <build>  
  2.     <plugins>  
  3.         <plugin>  
  4.             <groupId>org.danlleygroupId>  
  5.             <artifactId>maven-velocity-pluginartifactId>  
  6.             <version>1.0version>  
  7.             <configuration>  
  8.                 <template>sample_data.propertiestemplate>  
  9.             configuration>  
  10.             <executions>  
  11.                 <execution>  
  12.                     <phase>compilephase>  
  13.                     <goals>  
  14.                         <goal>replacegoal>  
  15.                     goals>  
  16.                 execution>  
  17.             executions>  
  18.         plugin>  
  19.     plugins>  
  20. build>  

 

 

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

F:\workspaces\maven-velocity-lab>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

分享到:
评论

相关推荐

    eclipse-maven2插件

    当Eclipse集成Maven2插件后,开发者可以在IDE内直接编辑POM.xml,插件会根据配置自动下载和管理所需的依赖库,避免了手动下载和配置库文件的繁琐工作。 Eclipse Maven2插件的主要功能包括: 1. **依赖管理**:插件...

    maven velocity

    2. **配置Velocity插件**:Maven有许多插件可以帮助处理Velocity模板,例如`velocity-maven-plugin`。在`pom.xml`的`build`部分,配置这个插件,指定模板目录、输出目录和模板引擎的其他设置。 3. **编写Velocity...

    springMVC+maven+velocity+数据源配置

    springMVC架构,maven , velocity , 数据源配置在项目中(springMVC的配置文件中)。

    m2maven是maven管理插件

    在提供的压缩包文件名称"0.10.2.20100623-1649"中,我们可以推测这是m2maven插件的一个特定版本,发布于2010年6月23日,具体版本号可能是0.10.2,这表明m2maven插件在较早的时候就已经存在,并且持续更新以适应不断...

    apache-maven的插件包:apache-maven-3.3.9-bin.zip

    2. `lib/`:存放了Maven运行所需的JAR文件,包括Maven核心库和其他依赖。 3. `conf/`:包含`settings.xml`文件,这是用户级的Maven配置文件,可以设置本地仓库位置、代理服务器、镜像等。 4. `LICENSE`和`NOTICE`...

    Maven的Settings的较为不错的文件以及配置介绍

    Maven是一个流行的Java项目管理工具,它使用一个名为settings.xml的配置文件来配置Maven的行为。settings.xml文件包含了Maven的全局设置,包括仓库位置、代理设置、构建配置等。 在Maven中,settings.xml文件通常...

    maven离线安装包(含环境配置文件)

    在Eclipse中,我们需要安装M2E(Maven Integration for Eclipse)插件,它可以帮助我们直接在IDE中管理和构建Maven项目。通过离线包,我们可以避免在线安装插件时可能出现的网络问题。 配置Eclipse与Maven的步骤...

    eclipse安装maven插件需要包

    Eclipse是一款广受欢迎的Java开发集成环境,而Maven则是一个强大的项目管理和构建工具...通过配置Windows的Maven环境和在Eclipse中进行离线安装,我们可以确保开发过程中对Maven的正常使用,实现项目的高效管理和构建。

    Maven的ssm项目配置文件

    在本主题中,我们将深入探讨Maven如何管理和组织SSM项目的配置文件,以及这些配置文件的主要功能。 1. Maven项目结构与配置: Maven是一个强大的构建工具,它通过一个统一的项目对象模型(Project Object Model, ...

    Maven原版settings.xml配置文件(下载)

    Maven原版settings.xml配置文件,根据个人需要,可以打开对应注释或替换相关阿里云镜像或远程仓库地址即可使用。

    eclipse离线安装maven插件(m2e),maven插件离线安装包

    现在eclipse的社区版都不内置maven插件了,站点在线安装实在是太痛苦了(我装了6个小时),于是急于寻找一种离线安装的办法,可是在网上又找不到对应的m2e包(我用的eclipse4.7),于是我决定将站点下的文件(很多)...

    IDEA插件推荐之Maven-Helper的教程图解

    Maven-Helper 插件是 IntelliJ IDEA 中的一款功能强大且实用的插件,旨在帮助开发者更好地管理 Maven 项目的依赖关系。下面是 Maven-Helper 插件的主要知识点: 1. 依赖关系查看:Maven-Helper 插件提供了一个简洁...

    maven搭建spring mvc velocity+mybatis

    首先,Maven是Apache的一个项目管理工具,它通过一个XML配置文件管理项目的依赖关系,构建过程以及报告。在"maven搭建spring mvc"的过程中,Maven将负责下载所需的库,编译源代码,运行测试,并打包应用为可部署的...

    Eclipse的Maven2插件.zip

    官网公布的 Eclipse 的 Maven2 插件,本插件版本是:m2e-0.12.0.20101115-1102,大小 11 MB。 关于安装 Maven2 插件到 Eclipse 的详细步骤,请参考博客《集成 Maven 2 插件到 eclipse 的过程》,博客地址:...

    Maven 整合 Spring mvc + Mybatis + Velocity 的实例

    2. **配置Spring MVC**:在src/main/webapp/WEB-INF下创建spring-servlet.xml文件,配置Spring MVC的相关组件,如DispatcherServlet、ViewResolver、Controller等。还可以利用注解配置@Controller和@RequestMapping...

    eclipse maven 离线插件

    2. **搜索并安装Maven插件**:在Marketplace的搜索框中输入“maven”,找到M2E (Maven Integration for Eclipse)插件,点击`Install`进行安装。遵循安装向导完成安装过程,可能需要重启Eclipse。 3. **配置Maven...

    maven仓库插件

    在`pom.xml`文件中,我们可以通过`&lt;build&gt;`标签下的`&lt;plugins&gt;`部分来配置和使用Maven插件。例如,为了配置Maven仓库插件,我们需要指定插件的groupId、artifactId、version以及可能的执行目标和参数。 ```xml ...

    eclipse-maven插件

    2. **解压插件文件**:将下载的插件文件解压,通常会得到一个`plugins`和`features`两个目录。这两个目录包含了插件的组件和特性描述。 3. **安装插件**:打开Eclipse,选择“Help” -&gt; “Install New Software”,...

Global site tag (gtag.js) - Google Analytics