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 @Override 15 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="周傑倫"; @Override public void play(){ System.out.println("播放:"+title+"來自藝術家:"+artist); } }
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等注解的使用方法與參數是多樣的。
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{ @Autowired private CompactDisc cd; @Autowired private MediaPlayer player; @Test public void test() { player.player(); cd.play(); assertNotNull(cd); assertNotNull(player); } }
熱愛分享拒絕拿來主義,博客精神永存——cvrigo
2016-11-09 00:19:44