欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring IOC中Bean的作⽤域与⽣命周期

程序员文章站 2022-03-19 15:01:46
...

Bean的作⽤域与⽣命周期

1.Bean的作⽤域

默认情况下,我们从Spring容器中拿到的对象均是"单例"的,对于bean的作⽤域类型如下:

singleton 作⽤域

Spring IOC中Bean的作⽤域与⽣命周期
注意: lazy-init是懒加载, 如果等于true时作⽤是指Spring容器启动的时候不会去实例化这个bean,⽽是在程序调⽤时才去实例化. 默认是false即Spring容器启动时实例化.
实例:

 // 得到Spring容器上下⽂环境
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");

这个就是spring容器的启动,如果没设置lazy-init的话就不会去实例这个bean。

// 得到UserController实例化对象
        UserController userController = (UserController) ac.getBean("userController");

这个就是得到controller的实例,这个时候就会创建bean的实例。

lazy-init设置为false的好处

1)可以提前发现潜在的配置问题
​ 2)Bean 对象存在于缓存中,使⽤时不⽤再去实例化bean,加快程序运⾏效率

适合作为单例的对象

就是作为适合创建bean例的类,⼀般来说对于⽆状态或状态不可改变的对象适合使⽤单例模式。(不存在会改变对象状态的成员变量)比如:user类定义的是各种属性,但有的时候我们需要的只是user属性的一小部分,所以user就不适合作为单例,而controller层、service层、dao层里面的类似固定的操作固定的属性,不会发生什么变动,所以适合作为单例。

2. prototype 作⽤域

Spring IOC中Bean的作⽤域与⽣命周期
通过scope=“prototype” 设置bean的类型 ,每次向Spring容器请求获取Bean都返回⼀个全新的Bean,相对于"singleton"来说就是不缓存Bean,每次都是⼀个根据Bean定义创建的全新Bean。

// 得到UserController实例化对象
        UserController userController = (UserController) ac.getBean("userController");

就是实例的时候,每次拿到的对象都是新建的。

Bean的⽣命周期

在Spring中,Bean的⽣命周期包括Bean的定义、初始化、使⽤和销毁4个阶段。

1.Bean的定义

在Spring中,通常是通过配置⽂档的⽅式来定义Bean的。在⼀个配置⽂档中,可以定义多个Bean。

2. Bean 的初始化

⽅式⼀:在配置⽂档中通过指定 init-method 属性来完成。

public class RoleService {
// 定义初始化时需要被调⽤的⽅法
public void init() {
System.out.println("RoleService init...");
}
}
<!-- 通过init-method属性指定⽅法 -->
<bean id="roleService" class="com.xxxx.service.RoleService" init-
method="init"></bean>

⽅式⼆: 实现 org.springframework.beans.factory.InitializingBean 接⼝。

public class RoleService implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("RoleService init...");
}
}
<bean id="roleService" class="com.xxxx.service.RoleService" ></bean>

3. Bean 的使⽤

⽅式⼀:使⽤ BeanFactory

// 得到Spring的上下⽂环境
BeanFactory factory = new ClassPathXmlApplicationContext("spring.xml");
RoleService roleService = (RoleService) factory.getBean("roleService");

⽅式⼆:使⽤ ApplicationContext

// 得到Spring的上下⽂环境
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
RoleService roleService = (RoleService) ac.getBean("roleService");

4. Bean的销毁

步骤⼀:实现销毁⽅式(Spring容器会维护bean对象的管理,可以指定bean对象的销毁所要执⾏的⽅法)

<bean id="roleService" class="com.xxxx.service.RoleService" destroy-
method="destroy"></bean>

步骤⼆:通过 AbstractApplicationContext 对象,调⽤其close⽅法实现bean的销毁过程

AbstractApplicationContext ctx=new
ClassPathXmlApplicationContext("spring.xml");
ctx.close();
相关标签: ioc