JSP Spring 自動(dòng)化裝配Bean實(shí)例詳解
Spring 自動(dòng)化裝配Bean
聲明一張cd的接口:
public interface CompactDisc { public abstract void play(); }
實(shí)現(xiàn)cd接口:
@Component("SgtPeppers") 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); } }
聲明cdplayer:
@Component("CDplayer")//表明該類作為組件類,沒(méi)必要顯示的配置Bean實(shí)例,括號(hào)內(nèi)為組件名 public class CDPlayer { /* * @Autowired注解可以用在構(gòu)造器上,也可以用在set方法上,也能直接放在下列代碼所示地方 * spring會(huì)滿足有該注解的依賴,如果只有一個(gè)bean匹配依賴需求的話,這個(gè)bean就會(huì)被裝配進(jìn)來(lái) @Autowired 默認(rèn)按類型裝配 * */ @Autowired private CompactDisc cd; public CompactDisc getCd() { return cd; } public void setCd(CompactDisc cd) { this.cd = cd; } public void play(){ cd.play(); } }
測(cè)試類:
public class CDPlayerTest { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); CDPlayer cdPlayer= (CDPlayer) context.getBean("CDplayer"); cdPlayer.play(); } }
xml:自動(dòng)掃描包,尋找有注解的類
<context:component-scan base-package="com.xue.soundsystem"></context:component-scan>
總結(jié):@Component:相當(dāng)于xml的bean中添加其實(shí)例,括號(hào)內(nèi)為id。@Autowired會(huì)按類型尋找匹配的實(shí)例進(jìn)行匹配。@Resource可以按照名字進(jìn)行裝配。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
jsp頁(yè)面數(shù)據(jù)分頁(yè)模仿百度分頁(yè)效果(實(shí)例講解)
下面小編就為大家?guī)?lái)一篇jsp頁(yè)面數(shù)據(jù)分頁(yè)模仿百度分頁(yè)效果(實(shí)例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07java Freemarker頁(yè)面靜態(tài)化實(shí)例詳解
這篇文章主要介紹了java Freemarker頁(yè)面靜態(tài)化實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04JSP頁(yè)面中文參數(shù)的傳遞(get和post方法分析)
JSP頁(yè)面中文參數(shù)傳遞在實(shí)際的編程中是十分有用的,get和post方法更是十分的常見(jiàn),那如何掌握好這些方法呢?本文將會(huì)向你實(shí)現(xiàn)這些方法的具體事宜2013-08-08JSP中使用JDBC訪問(wèn)SQL Server 2008數(shù)據(jù)庫(kù)示例
這篇文章主要介紹了JSP中使用JDBC訪問(wèn)SQL Server 2008數(shù)據(jù)庫(kù)示例,本文重點(diǎn)在JSP代碼示例中,需要的朋友可以參考下2014-09-09