Spring的ioc容器如何创建bean实例的?
- 在 Spring 的 IOC 容器配置文件里(applicationContext.xml)设置需要初始化的Bean
<!-- 配置bean对象 class:bean的全类名,通过反射的方式在IOC容器中创建Bean的对象,所以要求Bean中必须要有无参构造器
id:标识容器中的bean,id值唯一 -->
<bean id="helloWorld" class="com.zc.cris.HelloWorld">
<property name="name" value="cris"></property>
</bean>
在实例化bean之前需要首先实例化Spring ioc 容器
- 在 Spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用
Spring 提供了两种类型的 IOC 容器实现
- BeanFactory: IOC 容器的基本实现.
ApplicationContext: 提供了更多的高级特性. 是 BeanFactory 的子接口
BeanFactory 是 Spring 框架的基础设施,面向 Spring 本身;ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
- 从ioc容器中根据id获取bean对象实例
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
- ioc初始化bean对象的时候,就可以对其属性进行赋值,一般都是通过setter方法注入,也可以通过构造器进行注入
<!-- 通过setter方法注入属性值 -->
<bean id="helloWorld" class="com.zc.cris.HelloWorld">
<property name="name" value="cris"></property>
</bean>
<!-- 通过构造器的方法为bean注入属性值 -->
<bean id="car1" class="com.zc.cris.Car">
<constructor-arg value="法拉利" index="0"></constructor-arg>
<constructor-arg value="意大利" index="1"></constructor-arg>
<constructor-arg value="2000000.0" type="java.lang.Double"></constructor-arg>
</bean>
<!-- 使用构造器注入属性值可以指定参数的位置和类型,以区分重载的构造器 -->
<bean id="car2" class="com.zc.cris.Car">
<constructor-arg value="宝马" type="java.lang.String"></constructor-arg>
<constructor-arg value="德国"