少学习多摸鱼

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 @ 2023-07-25 18:59  北海之上  阅读(35)  评论(0)    收藏  举报
/* 粒子吸附*/