1. 程式人生 > >獲取IOC容器中的bean的兩種方式(id和class)的區別

獲取IOC容器中的bean的兩種方式(id和class)的區別


	
		// ClassPathXmlApplicationContext: 是 ApplicationContext的實現類,從類路徑下來載入配置檔案
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        //2.從IOC容器中獲取bean例項
        //利用id定位到IOC容器中的bean
        HelloWorld helloWorld=(HelloWorld)ctx.getBean("helloWorld");
        //用下面這種方式的話,利用型別返回IOC容器中的bean,但要求該容器中只有一個該型別的bean
        //就是說xml檔案中不能有兩個用同樣的類的bean
        HelloWorld helloWorld2=ctx.getBean(HelloWorld.class);
      
    

}

一種使用bean的id來獲取bean例項,這種方法比較實用
還一種就是使用bean的實現類,但是注意,當你的配置檔案xml中如果有兩個以上的bean使用同一個實現類的時候,就會報錯。