《LINUX教程:Spring自動化裝配bean》要點:
本文介紹了LINUX教程:Spring自動化裝配bean,希望對您有用。如果有疑問,可以聯系我們。
用CD(Compact disc)和CD播放器(CDPlayer)闡述DI(依賴注入).如果不將CD插入(注入)到CDPlayer中,那么CDPlayer其實沒有太大的用處,所以,可以這樣說:CDPlayer依賴于CD能力完成它的使命.
接口: CompactDisc.java
package soundsystem; public interface CompactDisc { void play(); }
接口: MediaPlayer.java
package soundsystem; public interface MediaPlayer { void play(); }
SgtPeppers.java
package soundsystem; import org.springframework.stereotype.Component; @Component public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles"; @Override public void play() { System.out.println("Playing " + title + " by " + artist); } }
注:SgtPeppers類上使用了@Component注解.這個簡單的注解注解該類會作為組件類,并告知Spring要為這個類創建bean
CDPlayer.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CDPlayer implements MediaPlayer { private CompactDisc cd; @Autowired public CDPlayer(CompactDisc cd) { this.cd = cd; } @Override public void play() { cd.play(); } }?
不過,組件掃描默認是不啟用的,我們還需顯式配置一下Spring,從而命令它去尋找帶有@Component表明的類,并未其創建bean.下例中使用了@ComponentScan表明,這個表明能夠在Spring中啟用組件掃描.如沒有其他配置,@ComponentScan默認會掃描與配置類相同的包:soundsystem
CDPlayerConfig.java
package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class CDPlayerConfig { }?
測試CDPlayerTest.java
package soundsystem; import static org.junit.Assert.*; import org.junit.Test; import org.junit.contrib.java.lang.system.StandardOutputStreamLog; 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 MediaPlayer player; @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); } @Test public void play() { player.play(); } }
自動裝配就是讓Spring自動滿足bean依賴的一種辦法,在滿足依賴的過程中,會在Spring應用的上下文中尋找匹配某個bean需求的其他bean.為了聲明要進行自動裝配,我們借助Spring的@Autowired注解.
上述代碼中,在構造器中添加了@Autowised注解,這注解當Spring創建CDPlayer bean的時候,會通過這個構造器來進行實例化,并傳入一個可設置為CompactDisc類的bean,在上面的代碼中,SgtPeppers被聲明為組件,并實現了CompactDisc接口.因此,在實際運行中會把SgtPeppers作為實例化類.
本文永遠更新鏈接地址:
維易PHP培訓學院每天發布《LINUX教程:Spring自動化裝配bean》等實戰技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養人才。