Plexus,Spring之外的IoC容器

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項目:

1 mvn archetype:create /
2   -DarchetypeGroupId=org.apache.maven.archetypes /
3   -DgroupId=demo /
4   -DartifactId=plexus-demos

生成項目後,在 pom.xml 加入所需的依賴包:

1 <dependencies>
2     <dependency>
3         <groupId>org.codehaus.plexus</groupId>
4         <artifactId>plexus-container-default</artifactId>
5         <version>1.0-alpha-10</version>
6     </dependency>
7 </dependencies>

Plexus與Spring的IoC容器在設計模式上幾乎是一致的,只是語法和描述方式稍有不同。在Plexus中,有ROLE的概念,相當於Spring中的一個Bean。我們首先來通過接口定義一個role:

01 package demo.plexus-demos;
02   
03 public interface Cheese
04 {
05     /** The Plexus role identifier. */
06     String ROLE = Cheese.class.getName();
07   
08     /**
09      * Slices the cheese for apportioning onto crackers.
10      * @param slices the number of slices
11      */
12     void slice( int slices );
13   
14     /**
15      * Get the description of the aroma of the cheese.
16      * @return the aroma
17      */
18     String getAroma();
19 }

然後做一個實現類:

01 package demo.plexus-demos;
02   
03 public class ParmesanCheese
04     implements Cheese
05 {
06     public void slice( int slices )
07     {
08         throw new UnsupportedOperationException( "No can do" );
09     }
10   
11     public String getAroma()
12     {
13         return "strong";
14     }
15 }

接下來是在xml文件中定義依賴注入關係。這一點和Spring的ApplicationContext是幾乎一樣的,只不過Plexus的xml描述方式稍有不同。另外,Plexus默認會讀取項目的classpath的META-INF/plexus/components.xml,因此我們在項目中創建 src/main/resources/META-INF/maven目錄,並將配置文件components.xml放置於此。配置文件的內容如下:

1 <component-set>
2   <components>
3     <component>
4       <role>demo.plexus-demos.Cheese</role>
5       <role-hint>parmesan</role-hint>      
6       <implementation>demo.plexus-demos.ParmesanCheese</implementation>
7     </component>
8   </components>
9 </component-set>

大功告成,接下來只需要做一個使用Cheese組件的類來試用一下:

01 import org.codehaus.plexus.PlexusContainer;
02 import org.codehaus.plexus.PlexusContainerException;
03   
04 public class App
05 {
06     public static void main(String args[]) throws Exception
07     {
08         PlexusContainer container= new DefaultPlexusContainer();
09         container.dispose();
10           
11         Cheese cheese = (Cheese) container.lookup( Cheese.ROLE, "parmesan" );
12         System.out.println( "Parmesan is " + cheese.getAroma() );
13     }
14 }
發佈了70 篇原創文章 · 獲贊 5 · 訪問量 47萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章