Spring核心容器之Bean
在Spring中,有两个最基本,最常用的包,即org.springframework.beans 和 org.springframework.context。在这两个包中,为了实现一种无侵入式的框架,代码中引用了大量的java反射机制,通过动态调用的方式避免了硬编码,为Spring的反向控制提供了基础。
在这两个包中有两个重要的类,BeanFactory 和ApplicationContext,BeanFactory提供了一中先进的配置机制来管理类型的Bean.ApplicationContext建立在BeanFactory上,并且增加了他的功能,提供对于国际化的支持,获取资源,时间传递等
id,name
Spring 中可以用id,name作为bean的id,并且至少一个指定一个id,id属性允许指定一个bean的id并且他能够在xmldtd中作为真正的ID元素被标记,所以对命名要遵循一定的规范,增加别名通过name属性指定一个或多个id,他们要有“,”,“;”,分割。一般用id指定备案的id
!!一个bean一般只有一个id,如果一个bean有超过一个的id,那么另外的id则看成是这个bean的别名
class
class 指明了bean的来源 (com.**)
Singleton 与 non-singleton
bean的两张部署模式,默认是Songleton,表示这个Bean,只有一个共享的实例存在,所有对这个bean的请求的都会返回这个唯一的实例 在bean的配置中 为 Songleton=“true”
另外一种为non-songleton ,表示每一次对这个bean的请求都会返回一个新的实例,相当于new,Songleton=“false”
ref 参考
<bean id="" class="">
<property name="">
<value></value>
</property>
<property name="">
<ref bean="date">
</property>
<bean id="date" class="">
</bean>
ref 的目的是添加其他的bean 或者是给对象的私有变量进行赋值等
NULL值
在spring中对null的处理有一下两种
<bean>
<property name="">
<value>null</value>
或者
<null/>
</property>
</bean>
使用依赖depends-on
书中简单的描述了depends-on的使用方式,对于其使用场景和使用的目的没有实例,通过寻找得出答案,
depends-on更多的时候是为了控制初始化的顺序,比如系统的初始化的时候,设置一些默认的参数,而缓存刷新管理器,需要用到系统初始化中设置的时间,所以在bean中配置前置依赖来保证系统bean在缓存之前加载成功
Bean的生命周期:
Bean的定义,Bean的初始化,Bean的使用,Bean的销毁
定义:就是通过配置文件进行相关的配置为定义
初始化:1.在配置文件中通过指定的init——method属性来完成
(1) 去掉该类的构造方法 (2) 增加一个init()方法 (3)在配置文件的对应bean中增加init-method ="init"
这样在创建的时候先初始化init
2.通过org.springframework.beans.factory.initalizingBean接口
如果一个bean实现了org.springframework.beans.factory.initalizingBean接口,则他的所有必需的属性被BeanFactory设置后,会自动执行afterPropertiesSet()方法!!!
(1)对应的java类实现initalizingBean
(2)增加一个方法afterPropertiesSet()用来完成初始化工作
Bean的使用:
1. 使用BeanWrapper
Hello hello =new Hello();
BeanWrapper bew=new BeanWrapperImpl(hello);
bw.setPropertyValue("msg","hello");
2. 使用BeanFactory
InputStream is =new FileInputStream("config.xml")
XmlBeanFactory factory=new XmlBenaFactory(is);
Hello hello=(Hello)factory.getBean("Hello");
3. 使用ApplicationContext
ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml")
Hello hello =(Hello)actx.getBean("Hello");
Bean的销毁
1.通过配置文件的destroy-method 来销毁
(1) 在类中编写clearup()(2) 在配置文件中 配置destroy-method 为clearup
2.实现org.springframework.beans.factory.DisposableBean接口
增加destroy方法