六、Bean
1、Bean的配置项
Id: 整个IOC容器中该bean的唯一标识
Class: 具体实例化的类
Scope: 范围(作用域)
Constructor arguments:构造器的参数
Properties: 属性
Autowriring mode: 自动装配的格式
lazy-initialization mode:
Initialization/destruction method:初始化和销毁的方法
2、Bean的作用域
singleton:单例,指一个Bean容器中指存在一份。
案例:配置(已知已存在一个类beanScope)
<bean id="beanScope" class="对应类的路径.beanScope" scope="beanScope"></bean>
prototype:每次请求(每次使用)创建新的实例,destory方法不生效。
<bean id="beanScope" class="对应类的路径.beanScope" scope="prototype"></bean>
request:每次http请求创建一个实例且仅在当前request内有效。
session:同上,每次http请求创建,当前session内有效。
global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session。(从一个系统通过链接跳到另一个系统,这个时候使用到global session)
3、Bean的生命周期
(1) bean定义
(2) 初始化
- 实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
public class ExampleBean implements InitializingBean{
@Override
public void afterPropertiesSet()throws Exception{
}
}
“
- 配置init-method
<bean id="exampleInitBean" class="类路径" init-method=“init”/>
public class ExampleBean{
public void init(){
}
}
(3)使用
(4) 销毁
- 实现org.springframework.beans.factory.DisposableBean接口,覆盖destory方法
public class ExampleBean implements DisposableBean{
@Override
public void destory()throws Exception{
}
}
- 配置init-method
<bean id="exampleInitBean" class="类路径" destory-method=“cleanup”/>
public class ExampleBean{
public void cleanup(){
}
}
- 配置全局默认的初始化、销毁方法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
default-init-method="init" default-destory-method="destory">
</beans>
注:当三种方式同时使用时,调用顺序是:先执行初始化和接口,而默认的方法会不生效。
配置了默认,但是没有实现方法,编译不会报错,但是配置了初始化,不实现方法,编译会报错。
4、Bean的自动装配
4.1 Aware
Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以获取相应的资源。
通过Aware接口,可以对Spring相应资源进行操作(一定慎用)
为对Spring进行简单的扩展提供了方便的入口。
5、Resourse&ResourseLoader
(未完待续)