Spring获取bean的三种方式
1.根据bean的id获取
根据id获取的bean一定是唯一的,但是一般需要强转对象来获取到
2.根据bean的类型获取(注意根据类型获取bean时,要求ioc容器中只有一个类型匹配的bean)
根据类型获取是用到最多的,一般在配置文件种一个类对应一个id
3.根据bean的id和类型获取
这样获取到的一定是唯一的
以下为测试代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentOne" class="com.qcw.spring.pojo.Student"></bean>
</beans>
@Test
public void testIOC(){
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
//根据bean的id获取
// Student student = (Student)ioc.getBean("studentOne");
//根据bean的类型获取
Student student = ioc.getBean(Student.class);
//根据bean的id和类型获取
// Student student = ioc.getBean("studentOne", Student.class);
System.out.println(student);
}
}
拓展问题
如果组件类实现了接口,根据接口类型可以获取 bean 吗?
答:可以,前提是bean唯一
如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
答:不行,因为bean不唯一
结论
根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。