Plexus是什麼?它是一個IoC容器,由codehaus在管理的一個開源項目。和Spring框架不同,它並不是一個完整的,擁有各種組件的大型框架,僅僅是一個純粹的IoC容器。本文講解Plexus的初步使用方法。
Plexus和Maven的開發者是同一羣人,可以想見Plexus和Maven的緊密關係了。由於在Maven剛剛誕生的時候,Spring還不成熟,所以Maven的開發者決定使用自己維護的IoC容器Plexus。而由於Plexus的文檔比較爛,根據社區的呼聲,下一版本的Maven 3則很可能使用比較成熟的Guice框架來取代Plexus,但更換底層框架畢竟不是一件輕鬆的事情,所以現階段學習瞭解Plexus還是很有必要的。並且Plexus目前並未停止開發,因爲它的未來還未可知。除了Maven以外,WebWork(已經與Struts合併)在底層也採用了Pleuxs。
爲了學習使用Plexus,首先我們還是用Maven創建一個乾淨的java項目:
2 |
-DarchetypeGroupId=org.apache.maven.archetypes / |
4 |
-DartifactId=plexus-demos |
生成項目後,在 pom.xml
加入所需的依賴包:
3 |
< groupId >org.codehaus.plexus</ groupId > |
4 |
< artifactId >plexus-container-default</ artifactId > |
5 |
< version >1.0-alpha-10</ version > |
Plexus與Spring的IoC容器在設計模式上幾乎是一致的,只是語法和描述方式稍有不同。在Plexus中,有ROLE的概念,相當於Spring中的一個Bean。我們首先來通過接口定義一個role:
01 |
package demo.plexus-demos; |
03 |
public interface Cheese |
05 |
/** The Plexus role identifier. */ |
06 |
String ROLE = Cheese. class .getName(); |
09 |
* Slices the cheese for apportioning onto crackers. |
10 |
* @param slices the number of slices |
12 |
void slice( int slices ); |
15 |
* Get the description of the aroma of the cheese. |
然後做一個實現類:
01 |
package demo.plexus-demos; |
03 |
public class ParmesanCheese |
06 |
public void slice( int slices ) |
08 |
throw new UnsupportedOperationException( "No can do" ); |
11 |
public String getAroma() |
接下來是在xml文件中定義依賴注入關係。這一點和Spring的ApplicationContext是幾乎一樣的,只不過Plexus的xml描述方式稍有不同。另外,Plexus默認會讀取項目的classpath的META-INF/plexus/components.xml,因此我們在項目中創建 src/main/resources/META-INF/maven
目錄,並將配置文件components.xml放置於此。配置文件的內容如下:
4 |
< role >demo.plexus-demos.Cheese</ role > |
5 |
< role-hint >parmesan</ role-hint > |
6 |
< implementation >demo.plexus-demos.ParmesanCheese</ implementation > |
大功告成,接下來只需要做一個使用Cheese組件的類來試用一下:
01 |
import org.codehaus.plexus.PlexusContainer; |
02 |
import org.codehaus.plexus.PlexusContainerException; |
06 |
public static void main(String args[]) throws Exception |
08 |
PlexusContainer container= new DefaultPlexusContainer(); |
11 |
Cheese cheese = (Cheese) container.lookup( Cheese.ROLE, "parmesan" ); |
12 |
System.out.println( "Parmesan is " + cheese.getAroma() ); |