上一次的隨筆內容只是簡單的實現了Bean的裝配(依賴注入)java
今天來具體講講實現Bean裝配的三種經常使用方法:spring
自動化裝配app
使用javaConfig顯示裝配ide
使用xml裝配測試
通常來講,儘量地使用自動化裝配(spring的一大原則就是約定大於配置),在必要時使用javaConfig顯示裝配,實在不行才使用xml裝配this
本篇不涉及xml裝配spa
1、自動化裝配code
所謂自動化裝配,就是讓spring自動的發現上下文所建立的Bean,並自動知足這些Bean之間的依賴。xml
自動掃描須要在Config配置類里加上@ComponentScan註解:blog
@Configuration //@PropertySource("classpath:./test/app.properties") @ComponentScan public class CDPlayerConfig { // @Autowired // Environment env; // // @Bean // @Conditional(CDExistsCondition.class) // public CDPlayer cdPlayer(CompactDisc compactDisc){ // return new CDPlayer(compactDisc); // } // // @Bean //// @Primary // public CompactDisc sgtPeppers(){ // return new BlankDisc(); //// return new SgtPeppers(); // } // // @Bean // public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){ // return new PropertySourcesPlaceholderConfigurer(); // } // // @Bean // @Primary // public CompactDisc BeatIt(){ // return new BeatIt(); // } }
若是不須要再顯示配置Bean,那麼配置類裏能夠是空的,徹底交給Spring去自動配置。
既然要讓spring自動發現Bean,那麼在寫類的時候,咱們便要加上@Component註解,表示這是一個能夠被發現的Bean:
package CD_Play; import org.springframework.stereotype.Component; @Component("abc") public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles"; SgtPeppers(){} @Override public void play() { System.out.println("Playing " + title + " by " + artist); } }
這裏類是一張「CD」,他實現了CD接口,並具備play功能,咱們正準備把他放入「CD機」(CDPlayer)進行播放,如今咱們爲這個類加上了@Component註解,他就能夠被Spring自動掃描發現了。
如今Spring已經能夠發現這個類了,那麼要怎麼才能讓Spring直到這個類該裝配到哪裏去呢,這就須要咱們在須要裝配的地方加上@Autowired註解:
package CD_Play; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class CDPlayer implements MediaPlayer{ private CompactDisc cd; @Autowired CDPlayer(CompactDisc cd){ this.cd = cd; } // @Autowired // @Qualifier("abc") // public void setCd(CompactDisc cd) { // this.cd = cd; // } // public CDPlayer(CompactDisc cd){ // this.cd = cd; // } @Override public void play() { cd.play(); } }
這個@Autowired註解能夠加載構造器上,也能夠加載set方法上(如註釋中同樣),這樣Spring就會根據所須要的參數(這裏是CompactDisc類的參數)從建立好各個Bean的容器中找到匹配這個類型的Bean直接裝配進去。
最後放出測試類進行測試:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CDPlayerConfig.class) public class CDPlayerTest{ @Rule public final StandardOutputStreamLog log = new StandardOutputStreamLog(); @Autowired private MediaPlayer player; @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull(){ assertNotNull(cd); } @Test public void play(){ player.play(); assertEquals("Playing Sgt. Pepper's Lonely Hearts Club Band" + " by The Beatles\r\n", log.getLog()); } }
測試結果爲:
能夠看到測試經過,證實Bean已被建立並被正確的裝配到CDPlayer中正常工做。