IOC(获取bean三种方式)
1 . 根据id获取
由于 id 属性指定了 bean 的唯一标识,
所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。
2 . 根据类型获取
①指定类型的 bean 唯一 :
能够正常获取到。
package com.atguigu.spring.pojo;
public class Student {
private Integer sid;
private String sname;
private String gender;
public Student(Integer sid, String sname, String gender) {
this.sid = sid;
this.sname = sname;
this.gender = gender;
}
/**
* 涉及到反射,大部分通过反射创建实例化用的都是无惨构造
* 错误:NoSuchMethodException;
*/
public Student() {
}
............
get set toString
}
<?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">
<!--
spring提供的对象默认就是单列的
如果是多例:没必要设置多个bean标签,同一个类型的bean标签
-->
<bean id="studentOne" class="com.atguigu.spring.pojo.Student" ></bean>
<!-- <bean id="studentTwo" class="com.atguigu.spring.pojo.Student"></bean>-->
</beans>
//@Test
/**
*2.根据bean的类型获取:(用最多)
* 注意:要求IOC容器中有且只有一个类型匹配的bean
* 若没有任何一个类型匹配的bean,此时抛出异常
* 通过类型获取的时候:
* 如果ioc有多个类型匹配的bean:
* 就获取不到(报错:NoUniqueBeanDefinitionException)
* 如果ioc一个bean都没有:报错NoSuchBeanDefinitionException
*/
//获取ioc容器
ApplicationContext ioc=new ClassPathXmlApplicationContext("ApplicationContext.xml");
//获取bean
Student bean = ioc.getBean(Student.class);
System.out.println(bean);
3 . 根据bean的id和类型获取
<bean id="studentOne" class="com.atguigu.spring.pojo.Student" ></bean>
//@Test
/**
* 3.根据bean的id和类型获取
* 只要有id获取的一定是唯一的
*/
Student studentOne = ioc.getBean("studentOne", Student.class);
System.out.println(studentOne);
思考:
如果组件类实现了接口,根据接口类型可以获取 bean 吗?
可以,前提是bean唯一
如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
不行,因为bean不唯一
结论:根据类型来获取bean时,在满足bean唯一性的前提下,
只要返回的是true就可以认定为和类型匹配,能够获取到。
浙公网安备 33010602011771号