《LINUX教程:Spring自動(dòng)化裝配bean》要點(diǎn):
本文介紹了LINUX教程:Spring自動(dòng)化裝配bean,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
用CD(Compact disc)和CD播放器(CDPlayer)闡述DI(依賴注入).如果不將CD插入(注入)到CDPlayer中,那么CDPlayer其實(shí)沒(méi)有太大的用處,所以,可以這樣說(shuō):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注解.這個(gè)簡(jiǎn)單的注解注解該類會(huì)作為組件類,并告知Spring要為這個(gè)類創(chuàng)建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(); } }?
不過(guò),組件掃描默認(rèn)是不啟用的,我們還需顯式配置一下Spring,從而命令它去尋找?guī)в蠤Component表明的類,并未其創(chuàng)建bean.下例中使用了@ComponentScan表明,這個(gè)表明能夠在Spring中啟用組件掃描.如沒(méi)有其他配置,@ComponentScan默認(rèn)會(huì)掃描與配置類相同的包:soundsystem
CDPlayerConfig.java
package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class CDPlayerConfig { }?
測(cè)試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(); } }
自動(dòng)裝配就是讓Spring自動(dòng)滿足bean依賴的一種辦法,在滿足依賴的過(guò)程中,會(huì)在Spring應(yīng)用的上下文中尋找匹配某個(gè)bean需求的其他bean.為了聲明要進(jìn)行自動(dòng)裝配,我們借助Spring的@Autowired注解.
上述代碼中,在構(gòu)造器中添加了@Autowised注解,這注解當(dāng)Spring創(chuàng)建CDPlayer bean的時(shí)候,會(huì)通過(guò)這個(gè)構(gòu)造器來(lái)進(jìn)行實(shí)例化,并傳入一個(gè)可設(shè)置為CompactDisc類的bean,在上面的代碼中,SgtPeppers被聲明為組件,并實(shí)現(xiàn)了CompactDisc接口.因此,在實(shí)際運(yùn)行中會(huì)把SgtPeppers作為實(shí)例化類.
本文永遠(yuǎn)更新鏈接地址:
維易PHP培訓(xùn)學(xué)院每天發(fā)布《LINUX教程:Spring自動(dòng)化裝配bean》等實(shí)戰(zhàn)技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養(yǎng)人才。
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/12975.html