隱式的bean發現與自動裝配機制,bean裝配機制
使用beans.xml檔案進行bean的建立和注入通常是可行的,但在便利性上Spring提供了更簡單的方法——自動裝配接下來我們假設一個情境:我有若干播放器(MediaPlayer{CD播放器/MP3}),我也有很多媒體檔案例如(CompactDisc{CD光碟片/MP3檔案})。現在,我們需要建立兩個介面MediaPlayer/CompactDisc,然後建立他們的實現CDPlayer/CompactDisc_zhoujielun。注意:CompactDisc_zhoujielun是周杰倫的CD光碟片。代碼如下:
1 package com.spring.cd; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Component; 5 6 @Component//Spring自動建立bean 7 public class CDPlayer implements MediaPlayer{ 8 private CompactDisc cd; 9 10 @Autowired//表明Spring初始化後儘可能地去滿足bean的依賴,在這裡它注入了一個CompactDisc的對象11 public CDPlayer(CompactDisc cd){12 this.cd=cd;13 }14 @Override15 public void player() {16 System.out.println("wo yong CD!");17 }18 }
當然,我們也可以在建立bean時對它命名,在CDPlayer類中可以體會到。代碼如下:
package com.spring.cd;import org.springframework.stereotype.Component;@Component("ZhouJieLun")public class CompactDisc_zhoujielun implements CompactDisc{private String title="發如雪";private String artist="周杰倫";@Overridepublic void play(){System.out.println("播放:"+title+"來自藝術家:"+artist);}}接下來,我們需要啟用組件掃描,組件掃描過程是通過Java代碼來定義Spring的裝配規則。代碼如下:
package com.spring.cd;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@ComponentScan("com.spring.cd") //參數代表當前需要掃描的路徑,為空白預設為當前包路徑@Configuration("cd")//需要掃描的包名稱//通過java代碼定義spring的裝配機制public class CDPlayerConfig {}
值得注意的是,真正的實現過程與代碼主體非常複雜,@Component,@ComponScan,@Autowired,@Comfiguration等註解的使用方法與參數是多樣的。
為了實現可視化,我們建立一個JUnit4測試。代碼如下:
package com.spring.cd;import static org.junit.Assert.*;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes=CDPlayerConfig.class)public class CDPlayerTest{@Autowiredprivate CompactDisc cd;@Autowiredprivate MediaPlayer player;@Testpublic void test() {player.player();cd.play();assertNotNull(cd);assertNotNull(player);}}上下文建立成功。
熱愛分享拒絕拿來主義,部落格精神永存——cvrigo
2016-11-09 00:19:44