三、Spring Bean

一、spring bean 概述

  • 什么是spring bean

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

简而言之:构成程序主干结构的对象,并且由spring管理,称之为spring bean

二、spring 创建 bean 的三种方式

  1. 使用默认的构造器进行创建
<bean id="userService" class="com.lizza.service.impl.UserServiceImpl"></bean>

要求:必须要有默认构造器

  1. 使用普通工厂方法进行创建
<bean id="beanFactory" class="com.lizza.factory.BeanFactory"></bean>
<bean id="userDao" factory-bean="beanFactory" factory-method="getUserDao"></bean>

使用普通工厂方法创建Bean的步骤:

  1. 创建普通工厂对象
  2. 创建实例对象,需要指定普通工厂方法的实例和方法;
    使用factory-bean参数指定工厂对象,使用factory-method工厂方法
  1. 使用静态工厂方法进行创建
<bean id="userDao" class="com.lizza.factory.StaticBeanFactory" factory-method="getUserDao"></bean>

三、spring bean 的作用范围

使用bean标签的scope属性来限定,默认是singleton,常用的是singleton和prototype

  1. singleton:单例模式(默认)
  2. prototype:多列模式
  3. request:作用于web应用中请求范围
  4. session:作用于web应用中会话范围
  5. global-session:作用于集群环境中的会话范围(全局session),当不是集群环境是,它就是session
<bean id="userDao3" class="com.lizza.dao.UserDao" scope="singleton"></bean>
<bean id="userDao3" class="com.lizza.dao.UserDao" scope="prototype"></bean>

四、spring bean 的生命周期

1. 单例对象
  • 创建:随着spring容器的创建而创建(立即加载)
  • 存活:只要spring容器存活,对象就存在
  • 销毁:随着spring容器的销毁而销毁
  • 总结:单例对象的生命周期与spirng容器的生命周期相同
2. 多例对象
  • 创建:在使用对象的时候进行创建(延迟加载)
  • 存活:对象在使用的时候会一直存在
  • 销毁:当对象长时间不使用,并且没有其他对象引用的时候,会被Java的垃圾回收器回收

源码地址:https://github.com/KJGManGlory/spring-framework

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值