基于XML管理Bean
spring创建对象思路:
获取ioc容器通过配置文件获取,根据配置文件的bean标签创建的对象,
bean标签里面id设置的是唯一标识,跟创建对象没有关系,
bean标签里面的class解析xml的时候就可以获取bean标签的class属性值,就知道了要管理的对象所对应的类型,需要创建对象,类型是不确定的,因为ioc容器中可以配置多个bean,所以ioc容器中底层是通过反射+工厂模式创建对象,知道类型的全类名之后通过IOC底层的反射通过调用无惨构造方法创建对象。
实体类
public class Student {
private Integer sid;
private String sname;
private Integer age;
private String gender;
public Student() {
}
....
}
Applicationcontext.xml文件
<?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">
<!--基于xml管理bean-->
<!--
bean:配置一个bean对象,将对象交给ioc容器管理
id:bean的唯一标识
class:设置bean对象所对应的类型
-->
<!-- bean表示的就是spring中的一个组件,spring管理的对象-->
<!-- ioc容器中管理一个对象,也可以管理多个对象,就可以通过id唯一标识区别 -->
<bean id="studentOne" class="com.atguigu.spring.pojo.Student"></bean>
</beans>
测试方法
@Test
public void TestIOC(){
// 获取ioc容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("Applicationcontext.xml");
// 根据id获取bean
Student student=(Student)applicationContext.getBean("studentOne");
System.out.println(student);
}
获取bean的三种方式
如果组件类实现了接口,根据接口类型可以获取 bean 吗?
可以,前提是bean唯一
如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
不行,因为bean不唯一
总结:通过bean类型,bean所继承的类的类型,
bean所实现的接口的类型都可以获取bean。
class里面不能写接口,因为一个bean对应一个对象,接口类型连构造方法都没有,
过程用的是反射,通过无惨构造传递,写的只能是一个具体的类型
1. 根据当前某个bean的id获取
返回值是Object
@Test
public void TestIOC(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("Applicationcontext.xml");
// 根据id获取bean
Student student=(Student)applicationContext.getBean("studentOne");
System.out.println(student);
}
2. 根据bean的类型获取
通过类型获取的,获取的对象是当前类型的实例化对象。
注意:根据类型获取bean,要求ioc容器中有且只有一个类型匹配的bean
没有任何一个类型匹配的bean,此时抛出异常。
这种方法常用,因为ioc容器中一个类型的bean配置一个。
@Test
public void TestIOC(){
// 获取ioc容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("Applicationcontext.xml");
// 根据bean的类型获取
Student student = applicationContext.getBean(Student.class);
System.out.println(student);
}
3. 根据类型和id获取
@Test
public void TestIOC(){
// 获取ioc容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("Applicationcontext.xml");
// 根据根据类型和id获取bean
Student student = applicationContext.getBean("studentOne", Student.class);
System.out.println(student);
}