您的位置:首页 > 其它

使用Maven强制控制依赖和依赖组件的版本

2013-07-26 18:36 751 查看
前言:在此之前公司技术管理混乱,工程里依赖的第三方组件谁想引入什么就引入什么,一个工程里同一个类型的jar包甚至有多种版本,让人不胜其烦。于是下决心要解决这个问题,原本想通过在公司的Maven私服上只保存有我们需要的jar包即可,可是总觉得这样不够灵活和优雅,而且将来很可能要升级jar包,而且要保持旧的jar包,所以觉得还是采用可以配置的方法,原本以为要自己写Maven插件,后来在官方文档里找了下,还真的碰上了。当然了,这种东西,除了官方网站,基本上找不到其他的资料。于是动手研究了下,经过多次试验,终于掌握了其中的步骤:

       1)创建父pom.xml,所有工程的pom.xml都必须继承该pom.xml;

       2)我们的目标是控制Spring版本是:3.0.6.RELEASE;

       3)在父pom.xml中的<plugins>标签下添加以下配置:

<plugin>
       
<groupId>org.apache.maven.plugins</groupId>
       
<artifactId>maven-enforcer-plugin</artifactId>
       
<version>1.2</version>
       
<executions>
         
<execution>
           
<id>enforce-banned-dependencies</id>
           
<goals>
             
<goal>enforce</goal>
           
</goals>
           
<configuration>
             
<rules>
               <bannedDependencies>
                 <excludes>
                 
<exclude>org.springframework</exclude>
                 </excludes>

 
 <includes>

                  <include>org.springframework:*:[3.0.6.RELEASE]:jar</include>

                  </includes>
               </bannedDependencies>
             
</rules>
             
<fail>true</fail>
           
</configuration>
         
</execution>
       
</executions>
      </plugin>

     </plugins>

      4、把这个pom.xml部署到私服上(如何部署pom.xml到私服这个可以参考其他资料);

      5、然后就可以在继承了这个父pom.xml的项目中测试,比如做package动作,如果这个时候故意想使用Spring3.0.5RELEASE,则会报以下警告,导致打包失败:

        [WARNING] Rule 0: org.apache.maven.plugins.enforcer.BannedDependencies failed with message:
        Found Banned Dependency: org.springframework:spring-jdbc:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-tx:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-context:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-beans:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-asm:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-orm:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-aop:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-expression:jar:3.0.5.RELEASE
Found Banned Dependency: org.springframework:spring-core:jar:3.0.5.RELEASE
Use 'mvn dependency:tree' to locate the source of the banned dependencies.

       注意:

1)<include>和<excludes>的正则表达式的格式是:groupId[:artifactId][:version][:type][:scope][:classifier],其中artifactId,
version, type, scope 、classifier 是可选的。

       2)关于版本等方面如果正则表达式写成org.springframework:*:3.0.6.RELEASE:jar则表示大于等于3.0.6RELEASE这个版本,则是可以的,如果小于3.0.6.RELEASE则会报错,相当于数学里的开闭区间[)。这方面还有很多详细的资料,可以参考官方网站;

   
   3)注意,这个控制插件的1.2以上的版本使用起来有点问题,当然了,可能和我本地环境有关,大家可以试试,本人使用的是1.2版本;

   
   4)还可以用来控制JDK版本等,可以参考官方资料,网站地址为:该插件官方网址

      欢迎大家交流、拍砖。如有疑问,请和本人交流。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Maven 版本控制