SPRing從兩個角度實現自動化裝配:組件掃描 (Spring自動發現應用上下文中所創建的bean)自動裝配(autowiring)自動滿足bean之間的依賴
組件掃描:
package test.soundsystem;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import test.voice.Book;/* * 使用basePackageClasses,spring會自動掃描這些類所在的包, * 建議在包中寫空標記接口,用來被掃描,有利于項目重構。 * * */@Configuration@ComponentScan(basePackageClasses={Book.class,CompactDisc.class})public class CDPlayerConfig {}接口:package test.soundsystem;public interface CompactDisc { void play();}實現類:package test.soundsystem;import javax.inject.Named;//Named 和 Component相似@Namedpublic class SgtPeppers implements CompactDisc { private String title="Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles"; public void play() { System.out.println("Playing "+title+" by "+artist); }}測試類:package test.soundsystem;import javax.inject.Inject;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;import test.voice.Book;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes=CDPlayerConfig.class)public class CDPlayerTest { @Autowired private CompactDisc cd; @Inject private Book book; @Test public void cdShouldNotBeNull(){ cd.play(); book.read(); }}
新聞熱點
疑難解答