内容:
配置形式:基于XML文件的方式;基于注解的方式
Bean的配置方法:通过全类名(反射),通过工厂方式(静态工厂方式&实例工厂方式),FactoryBean
IOC容器BeanFactory&ApplicationContext概述
依赖注入的方式:属性注入,构造器注入
注入属性值细节
自动转配
Bean之间的关系:继承,依赖
Bean的作用域:singleton,prototype,WEB环境作用域
使用外部属性文件
spEL
IOC容器中Bean的生命周期
Spring4.x新特性:泛型依赖注入
在Spring的IOC容器里配置Bean
- 在xml文件中通过bean节点来配置bean
<!-- 通过全类名的方式配置bean -->
<!-- class: bean的全类名,表示是通过反射的方式在IOC容器中创建bean实例。所以要求在HelloWorld中必须有一个无参的构造函数,如果不存在这个无参的构造器,那么就会编译出错 -->
<!-- id: 标志容器中的bean,id唯一 -->
<bean id="helloWorld" class="com.atguigu.spring.beans.HelloWorld" >
<property name="name" value="World"></property>
</bean>
id: bean的名称
- 在IOC容器中必须是唯一的
- 若id没有指定,Spring自动将类名作为Bean的名字
- id可以指定多个名字,名字之间可用逗号,分号,或空格分隔
Spring容器
在Spring IOC容器读取Bean配置创建Bean实例之前,必须对他进行实例化,只有在容器实例化之后,才可以从IOC容器里获取Bean实例并使用。
Spring提供了两种类型的IOC容器实现
- BeanFactory, IOC的基本实现
- ApplicationContext 提供了更多的高级特性,是BeanFactory的子接口
- BeanFactory是Spring框架的基础设施,面向Spring本身;ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都直接使用ApplicationContext而非底层的BeanFactory
- 无论使用何种方式,配置文件是相同的
AplicationContext介绍
ApplicationContext的主要实现类:
- ClassPathXmlApplicationContext, 从类路径下加载配置文件
- FileSystemXmlApplicationContext,从文件系统中加载配置文件
ConfigurableContext扩展于ApplicationContext,新增加两个主要方法:refresh()和close() ,让ApplicationContext具有启动,刷新和关闭上下文的能力。
ApplicationContext在初始化上下文时就实例化所有实例的Bean
WebApplicationContext是专门为WEB应用而准备的,它允许从相对于WEB根目录的路径中完成初始化工作
代码实例:
// 创建Spring 的IOC 容器
// ApplicationContext 代表IOC容器
// ClassPathXmlApplicationContext: 是ApplicationContext 接口的实现类,该实现类从类路径下来加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//从IOC容器中获取bean实例
//通过id 定位到IOC容器中的be