Spring初探
Bean容器初始化
- 基础:两个包
org.springframework.beansorg.springframework.contextBeanFactory提供配置结构和基本功能,加载并初始化BeanApplicationContext保存了Bean对象所在Spring中被广泛使用
- 方式,ApplicationContext
- 本地文件
- classpath
- Web应用中依赖Servlet或Listener
Spring的常用注入方式
-
设值注入(必须有set方法)
<beans> <bean id="" class=""> <property name="" ref=""></property> </bean> <bean id="" class=""></bean> </beans> -
构造注入
<beans> <bean id="" class=""> <constructor-arg name="" ref=""></property> </bean> <bean id="" class=""></bean> </beans>
专题二
Bean配置项
- Id
- Class
- Scope
- Construtor arguments
- Properties
- Autowiring mode
- lazy-initialization mode
- Initialization/destruction method
Bean的作用域
- singleton:单例,指一个Bean容器中只存在一份
- prototype:每次请求(每次使用)创建新的实例,destory方式不生效
- request:每次http请求创建一个实例且仅在当前request内有效
- session:同上,每次http请求创建,当前session内有效
- global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session
Bean的生命周期
-
定义
-
初始化
- 实现org.springfrmaework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
public class ExampleBean implements InitializingBean { public void afterPropertiesSet() throws Exception { //do something } }- 配置init-method。
<bean id="" class="" init-method=""></bean>public class ExampleBean { public void init() { //do some initialization work } } -
使用
-
销毁
- 实现org.springframework.beans.factory.DisposableBean接口,覆盖destroy方法
public class ExampleDisposalBean implements DisposableBean {
public void destroy() throws Exception {
//do something
}
}
- 配置destory-method
<bean id="" class="" init-method=""></bean>
public class ExampleBean {
public void cleanup() {
//do some destruction work (like releasing pooled connections)
}
}
- 配置全局初始化,销毁方法
<beans default-init-method="" default-destroy-method=""></beans>

浙公网安备 33010602011771号