JSP Spring 自動化裝配Bean實例詳解
更新時間:2017年04月15日 09:27:17 投稿:lqh
這篇文章主要介紹了JSP Spring 自動化裝配Bean實例詳解的相關(guān)資料,需要的朋友可以參考下
Spring 自動化裝配Bean
聲明一張cd的接口:
public interface CompactDisc {
public abstract void play();
}
實現(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")//表明該類作為組件類,沒必要顯示的配置Bean實例,括號內(nèi)為組件名
public class CDPlayer {
/*
* @Autowired注解可以用在構(gòu)造器上,也可以用在set方法上,也能直接放在下列代碼所示地方
* spring會滿足有該注解的依賴,如果只有一個bean匹配依賴需求的話,這個bean就會被裝配進來
@Autowired 默認按類型裝配
* */
@Autowired
private CompactDisc cd;
public CompactDisc getCd() {
return cd;
}
public void setCd(CompactDisc cd) {
this.cd = cd;
}
public void play(){
cd.play();
}
}
測試類:
public class CDPlayerTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
CDPlayer cdPlayer= (CDPlayer) context.getBean("CDplayer");
cdPlayer.play();
}
}
xml:自動掃描包,尋找有注解的類
<context:component-scan base-package="com.xue.soundsystem"></context:component-scan>
總結(jié):@Component:相當(dāng)于xml的bean中添加其實例,括號內(nèi)為id。@Autowired會按類型尋找匹配的實例進行匹配。@Resource可以按照名字進行裝配。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Struts2中實現(xiàn)web應(yīng)用的初始化實例詳解
這篇文章主要介紹了Struts2中實現(xiàn)web應(yīng)用的初始化實例詳解的相關(guān)資料,需要的朋友可以參考下2017-06-06
通用彈出層頁面(兼容IE、firefox)可關(guān)閉控制寬高及屏蔽背景
本人搜集整理了一個通用彈出層頁面(兼容IE、firefox)可關(guān)閉控制寬高及屏蔽背景,需要的朋友可以了解下2012-12-12

