快速学习-IOC容器和Bean的配置

2.2 通过类型获取bean

  1. 从IOC容器中获取bean时,除了通过id值获取,还可以通过bean的类型获取。但如果同一个类型的bean在XML文件中配置了多个,则获取时会抛出异常,所以同一个类型的bean在容器中必须是唯一的。
HelloWorld helloWorld = cxt.getBean(HelloWorld. class);
  1. 或者可以使用另外一个重载的方法,同时指定bean的id值和类型
HelloWorld helloWorld = cxt.getBean(“helloWorld”,HelloWorld. class);
发布了1336 篇原创文章 · 获赞 1094 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/104266101