Spring 自動化裝配Bean

聲明一張cd的接口:spring

public interface CompactDisc {
    public abstract void play();
}

實現cd接口:app

@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:ide

@Component("CDplayer")//代表該類做爲組件類,不必顯示的配置Bean實例,括號內爲組件名
public class CDPlayer {
    /*
    * @Autowired註解能夠用在構造器上,也能夠用在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:自動掃描包,尋找有註解的類this

 <context:component-scan base-package="com.xue.soundsystem"></context:component-scan>

總結:@Component:至關於xml的bean中添加其實例,括號內爲id。@Autowired會按類型尋找匹配的實例進行匹配。@Resource能夠按照名字進行裝配。spa

相關文章
相關標籤/搜索