使用Maven強制控制依賴和依賴元件的版本
前言:在此之前公司技術管理混亂,工程裡依賴的第三方元件誰想引入什麼就引入什麼,一個工程裡同一個型別的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版本等,可以參考官方資料,網站地址為:該外掛官方網址
歡迎大家交流、拍磚。如有疑問,請和本人交流。