获取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使用同一个实现类的时候,就会报错。

猜你喜欢

转载自blog.csdn.net/qq_37774171/article/details/85231630