Bean的作用域和声明周期

Bean的作用域有 单例原型 两个作用域, 声明周期包括 定义初始化使用销毁 4个声明周期。

Bean的作用域

单例作用域

默认情况下,Bean对象都是单例的。

1
<bean scope="singleton" />

原型作用域

每次都生成一个新的bean对象

1
<bean scope="prototype" />

懒加载

可以使用bean标签的 lazy-init 属性设置是否懒加载, 默认为 false

如果为turespring容器启动的时候不会实例化bean,而是在程序调用时才实例化bean对象。

1
<bean lazy-init="true" />

Bean的生命周期

Bean定义

通常使用配置文件或注解定义Bean

Bean初始化

默认在IOC容器加载时,实例化对象;初始化有两种方式

  • 方式一 在配置文件中通过指定 init-method 属性来完成
1
2
3
4
5
public class RoleService {
public void init(){
...
}
}
1
<bean id="roleService" class="com.xxx.service.RoleService" init-method="init" />
  • 方式二 实现 org.springframework.beans.factory.InitialzingBean 接口

Bean使用

  • 方式一 使用 BeanFactory
1
2
BeanFactory factory = new ClassPathXmlApplicationContext("spring.xml");
RoleService roleService = factory.getBean("roleService", RoleService.class);
  • 方式二 使用 ApplicationContext
1
2
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
RoleService roleService = ac.getBean("roleService", RoleService.class);

Bean销毁

spring容器会维护bean对象的管理,可以使用 destory-method 属性指定bean对象销毁所要执行的方法。

  • 步骤一,使用 destory-method 属性指定bean对象销毁所要执行的方法。
1
<bean id="roleService" class="com.xxx.service.RoleService" destory-method="destroy"/>
  • 步骤二
1
2
AbstractApplicatoinContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ctx.close();