Spring学习笔记之配置bean

一、内容摘要

配置形式:基于 XML 文件的方式
Bean 的配置方式:通过全类名(反射)
IOC 容器 BeanFactory & ApplicationContext 概述

依赖注入的方式:属性注入;构造器注入


二、在 Spring 的 IOC 容器里配置 Bean

在 xml 文件中通过 bean 节点来配置 bean

<!-- 通过全类名的方式来配置 bean 
     class:bean 的全类名,通过反射的方式在 IOC 容器中创建 Bean,所以要求 Bean 中必须有无参数的构造器
     id:标识容器中的 bean,id唯一。
-->
<bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">
	<property name="name" value="Spring"></property>
</bean>


三、Spring 容器

在 spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用.
Spring 提供了两种类型的 IOC 容器实现. 
BeanFactory: IOC 容器的基本实现.
ApplicationContext: 提供了更多的高级特性. 是 BeanFactory 的子接口.
BeanFactory 是 Spring 框架的基础设施,面向 Spring 本身;ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory
无论使用何种方式, 配置文件是相同的.


四、ApplicationContext

ApplicationContext 的主要实现类:
ClassPathXmlApplicationContext:从 类路径下加载配置文件
FileSystemXmlApplicationContext: 从文件系统中加载配置文件
ConfigurableApplicationContext 扩展于 ApplicationContext,新增加两个主要方法:refresh() 和 close(), 让 ApplicationContext 具有启动、刷新和关闭上下文的能力
ApplicationContext 在初始化上下文时就实例化所有单例的 Bean。
WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作



五、依赖注入的方式

Spring 支持 3 种依赖注入的方式:
属性注入
构造器注入

工厂方法注入(很少使用,不推荐)


属性注入

属性注入即通过 setter 方法注入Bean 的属性值或依赖的对象
属性注入使用 <property> 元素, 使用 name 属性指定 Bean 的属性名称,value 属性或 <value> 子节点指定属性值 
属性注入是实际应用中最常用的注入方式

<!-- 通过全类名的方式来配置 bean 
     class:bean 的全类名,通过反射的方式在 IOC 容器中创建 Bean,所以要求 Bean 中必须有无参数的构造器
     id:标识容器中的 bean,id唯一。
-->
<bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">
	<property name="name" value="Spring"></property>
</bean>


构造方法注入

通过构造方法注入Bean 的属性值或依赖的对象,它保证了 Bean 实例在实例化后就可以使用。
构造器注入在 <constructor-arg> 元素里声明属性, 

需要注意的是:Spring4.0版本中 <constructor-arg> 中有 name 属性,没有 <name>子节点。

<!-- 通过构造方法来配置 bean 的属性 index:指定参数的索引-->
<bean id="car" class="com.atguigu.spring.helloworld.Car">
	<constructor-arg value="Audi" index="0"></constructor-arg>
	<constructor-arg value="ShangHai" index="1"></constructor-arg>
	<constructor-arg value="300000" index="2"></constructor-arg>
</bean>
<!-- 通过构造方法来配置 bean 的属性 type:指定参数的类型-->
<bean id="car2" class="com.atguigu.spring.helloworld.Car">
	<constructor-arg value="Audi" type="java.lang.String"></constructor-arg>
	<constructor-arg value="ShangHai" type="java.lang.String"></constructor-arg>
	<constructor-arg value="200" type="int"></constructor-arg>
</bean>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值