- bean的作用域
singleton:单例,指一个Bean容器中只存在一份。(默认)
prototype:每次请求(每次使用)创建心得实例,destroy方式不生效
request:每次http请求创建一个实例且仅在当前request内生效
session:同上,每次http请求创建,当前session内有效 global
session:基于portlet的web中有效,如果是在web中,同session
- bean的生命周期
bean的生命周期有:定义,初始化,使用,销毁。
初始化方法有三种实现方式:
1:在配置文件中:
<bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle" init-method="start" ></bean>`
在实现类中:
public void start() {
System.out.println("Bean start .");
}
2:在配置文件中不配置,实现org.springframework.beans.factory.InitializingBean借口,覆盖afterPropertiesSet方法。
在实现类中:
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean afterPropertiesSet.");
}
3:设置全局方法
<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.xsd"
default-init-method="defautInit" >
在实现类中:
public void defautInit() {
System.out.println(“Bean defautInit.”);
}
销毁方法同有三种实现方式:
1:在配置文件中:
<bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle" destroy-method="stop"></bean>`
在实现类中:
public void stop() {
System.out.println("Bean stop.");
}
2:在配置文件中不配置,实现org.springframework.beans.factory.DisposableBean借口,覆盖destroy方法。
在实现类中:
@Override
public void destroy() throws Exception {
System.out.println("Bean destroy.");
}
3:设置全局方法
<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.xsd"
default-destroy-method="defaultDestroy">
实现类:
public void defaultDestroy() {
System.out.println("Bean defaultDestroy.");
}
当spring的初始化和销毁的第1个和第二个方法已经定义和实现,那么,全局默认的方法既第三个方法则不会实现。