spring中bean的配置
1.配置形式:
(1) 基于XML文件的方式
1.在xml文件中通过节点来配置bean
2.id:Bean的名称
--- 在IOC容器中必须是唯一的--- 若id没有指定,Spring自动将权限定性类名作为Bean的名字
--- id可以指定多个名字,名字之间可用逗号,分号,或空格分隔
(2)基于注解的方式
2.Bean的配置方式:
(1)通过全类名(反射)
(2) 通过工厂方法(静态工厂方法&实例工厂方法)
(3)FactoryBean
3.IOC容器BeanFactory&ApplicationContext概述
( 1 ) SpringIOC容器
在Spring IOC容器读取Bean配置创建Bean实例之前,必须对它进行实例化,只有在容器实例化,才可以从IOC容器里获取Bean实例并使用。( 2 )IOC容器实现
Spring提供了两种类型的IOC容器实现
(1) BeanFactory IOC容器的基本实现
(2) ApplicationContext提供了更多的高级特性,是BeanFactory的子接口。
-BeanFactory是Spring框架的基础设施,面向Spring本身;
ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext而非底层的BeanFactory
-无论使用何种方式,配置文件是相同的。
(1) BeanFactory IOC容器的基本实现
(2) ApplicationContext提供了更多的高级特性,是BeanFactory的子接口。
-BeanFactory是Spring框架的基础设施,面向Spring本身;
ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext而非底层的BeanFactory
-无论使用何种方式,配置文件是相同的。
( 3 )ApplicatonContext
(1)ApplicatonContext代表 Spring 的IOC容器,是一个接口。
(2)ApplicationContext的主要实现类:
1.ClassPatnXmlApplicationContext:从类路径下加载配置文件
2.FileSystemXmlApplicationContext:从文件系统下加载配置文件
(3)ApplicatonContext的拓展类
(2)ApplicationContext的主要实现类:
1.ClassPatnXmlApplicationContext:从类路径下加载配置文件
2.FileSystemXmlApplicationContext:从文件系统下加载配置文件
(3)ApplicatonContext的拓展类
ConfigurationApplicationContext拓展于ApplicationContext,新增加两个主要方法:refresh()和close(),让ApplicationContext
具有启动,刷新和关闭上下文的能力。
WebApplicationContext是专门为WEB应用而准备的,它允许从相对于WEB根目录的路径中完成初始化工作。
4.依赖注入的方式:
(1)属性注入
属性注入即通过setter方法注入Bean的属性值或依赖的对象,
属性注入使用<property>元素,使用name属性指定Bean的属性名称,value属性或<value>字节点指定属性值。
属性注入是实际应用中最常用的注入方式
属性注入时:必须要求对应bean有无参的构造器和setter方法
(2)构造器注入
通过构造方法注入Bean的属性值或依赖的对象,它保证了Bean实例在实例化后就可以使用
构造器注入在<constructor-arg>元素里声明属性,<constructor-arg>中没有name属性
构造方法注入:必须要求bean有对应参数的构造器
使用构造器注入属性值可以指定参数的位置和参数的类型!以区分重载的构造器:
Car.java
(3)工厂方法注入(很少注入,不推荐)
Helloworld.java
applicationContext.xml
Main.java