Spring 学习之路(三):Spring IOC 详解(bean的配置)

本文详细介绍了Spring的IOC容器如何创建bean实例,包括通过XML配置文件初始化bean,BeanFactory与ApplicationContext的区别,以及bean的属性注入方式如setter注入和构造器注入。此外,还讲解了bean的字面值注入、引用注入、级联属性、集合属性赋值以及自动装配的byType和byName模式。提供了丰富的代码示例和配置细节。
摘要由CSDN通过智能技术生成
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 容器

    1. 在 Spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用
    2. Spring 提供了两种类型的 IOC 容器实现

      1. BeanFactory: IOC 容器的基本实现.
      2. ApplicationContext: 提供了更多的高级特性. 是 BeanFactory 的子接口

      3. 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="德国"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值