鱼少学习多摸

day119 - spring-获取bean

获取bean

根据id获取

上一篇的入门文章讲解的就是根据id获取bean的方式

根据类型获取

@Test
public void testIOC(){
    //获取ioc容器
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
    //获取bean
    Student student = ioc.getBean(Student.class);
    System.out.println(student);
}

 

根据id和类型获取

复制代码
@Test
public void testIOC(){
    //获取ioc容器
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
    //获取bean
    //Student studentOne = (Student) ioc.getBean("studentOne");
    //Student student = ioc.getBean(Student.class);
    Student student = ioc.getBean("studentOne", Student.class);
    System.out.println(student);
​
}
复制代码

 

注意

当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

如下:

<bean id="helloworldOne" class="com.gu.spring.HelloWorld"></bean> 
<bean id="helloworldTwo" class="com.gu.spring.HelloWorld"></bean>

 

会报错:

NoUniqueBeanDefinitionException:

总结:

根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

复制代码
/**
 * 获取bean的三种方式:
 * 1. 根据bean的id获取
 * 2. 根据bean的类型获取
 * 注意:根据类型获取bean时,要求ioc容器中有且只有一个类型匹配的bean
 * 若一个都没有,没有任何一个类型匹配的bean,抛出异常NoSuchBeanDefinitionException
 * 若有多个,抛出异常NoUniqueBeanDefinitionException
 * 3. 根据bean的id和类型获取
 * 结论:
 * 根据类型来获取bean时,在满足bean唯一性的前提下,
 * 其实只看对象 instanceof指定的类型的返回结果
 * 只要返回的是true就可以认定为类型匹配,能够获取到
 * 即通过bean的类型或者bean所继承的类或者所实现的接口的类型都可以获取bean
 */
复制代码

 

over

posted @   北海之上  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
/* 粒子吸附*/
点击右上角即可分享
微信分享提示