一.Spring Bean定义
Bean定义:bean是一个被实例化,组装,并通过Spring IoC容器所管理的对象。这些bean是由容器提供的配置元数据创建的。
bean定义包含称为配置元数据的信息,
*如何创建一个bean
*bean的生命周期的详细信息
*bean的依赖关系
二.bean的各种属性
(1)class属性,这个属性是强制性的,并且指定用来创建bean的bean类。
(2)name属性,指定唯一的bean标识符。在基于XML的配置元数据中,可以使用ID/name属性来指定bean标识符。
(3)scope属性,这个属性指定由特定的bean定义创建的对象的作用域。
(4)constructor-arg、properties、autowiring mode属性,用来注入依赖关系的。
(5)lazy-initialization mode延迟初始化的baen告诉IoC容器在它第一次被请求时,而不是在启动时去创建一个bean实例。
三.Spring配置元数据(Bean)
Spring IoC容器配置bean的格式:
1.基于XML的配置文件
2.基于注解的配置
3.基于Java的配置
四.Spring Bean作用域
1.singleton,在singleton IoC容器仅存在一个Bean实例,Bean以单例方式存在,默认值。
2.prototype,每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行newXxxBean()。
singleton作用域:
当一个bean作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean 的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。
Singleton是单例类型,就是在创建的时候容器就同时创建了一个bean对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。
prototype作用域:
当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会创建一个对象,而且我们每次获取到的对象都不是同一个对象。
五.Spring Bean的生命周期
六.Spring基于构造函数的依赖注入
1.基于构造函数的依赖注入
如果类A依赖于类B,类A创建构造函数时,将类B对象作为类A构造函数的参数注入到类A中。在bean.xml中类A的bean中声明,constructor-arg ref的属性值为类B。
类A,TextEditor.java:
public class TextEditro{
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor.");
this.spellChecker = spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
类B,SpellChecker.java
public class SpellCheckerP{
public SpellChecker(){
System.out.println("Inside SpellChecker constructor.");
}
public void checkSpelling(){
System.out.println("Inside checkSpelling");
}
}
MainApp.java
TextEditor te = (TextEditor)context.getBean("textEditor");
te.spellCheck();
Bean.xml
<bean id="textEditor" class="com.lee.TextEditor">
<constructor-arg ref = "spellChecker"/>
</bean>
<bean id ="spellChecker" class="com.lee.SpellChecker">
</bean>
输出顺序:
Inside SpellChecker constructor
Inside TextEditor constructor
Inside checkSpelling
2.set注入
当容器调用一个无参的构造函数或一个无参的静态factory方法来初始化bean,通过容器在你的bean上调用设值函数,基于设置函数的DI来完成依赖注入。
类A没有构造函数,直接创建类B的get/set方法,get/set方法的参数为类B类型。
构造函数注入和set注入的区别:
1.基于构造函数的注入,<使用的bean>标签中的<constructor-arg>元素;基于set注入,使用的<bean>标签中的<property>。
2.如果你要把一个引用传递给一个对象,使用标签ref属性。直接要传递一个值,使用value值。