Spring配置文件bean标签singleton、prototype、Bean实例化三种方式

本文介绍了Spring配置文件中bean的singleton和prototype两种作用域,详细阐述了它们的实例化过程。对于singleton,bean默认为单例模式,只会创建一个对象;而对于prototype,每次请求都会创建新的对象。此外,文章还详细讲解了Bean的三种实例化方式:1) 无参构造方法实例化,依赖于默认无参构造函数;2) 工厂静态方法实例化,通过静态方法返回Bean实例;3) 工厂实例方法实例化,利用非静态方法创建Bean对象。

先从这个项目里改:https://blog.youkuaiyun.com/GLOAL_COOK/article/details/112424735
配置文件:
在这里插入图片描述改applicationContext.xml文件,再在test测试

1.singleton

<bean id="userDao" class="cn.itcast.dao.impl.UserDaoImpl"></bean> 

不写scope就默认为singleton,也不可以不省略:

<?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.xsd">

    <!--这里的id是你随便起的,后面你getbean对应就行,然后class是写你要获取对象的全类名-->
    <bean id="userDao" class="cn.itcast.dao.impl.UserDaoImpl" scope="singleton"></bean>
</beans>

测试:
singleton的话对象只创建一次而已
在这里插入图片描述

2.prototype

<?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.xsd">

    <!--这里的id是你随便起的,后面你getbean对应就行,然后class是写你要获取对象的全类名-->
    <bean id="userDao" class="cn.itcast.dao.impl.UserDaoImpl" scope="prototype"></bean>
</beans>

把scope改为prototype,再运行test1结果:
在这里插入图片描述
prototype会创建多个对象的

上面把UserDaoImpl方法改下,我们测singleton和prototype的生命周期,修改它的无参构造方法:

package cn.itcast.dao.impl;

import cn.itcast.dao.UserDao;

/**
 * @author QLBF
 * @version 1.0
 * @date 2021/1/10 12:11
 */
public class UserDaoImpl implements UserDao {
    public UserDaoImpl() {
        System.out.println("UserDaoImpl被创建了");
    }

    public void save() {
        System.out.println("sping....coming!");
    }
}

总结:
在这里插入图片描述

3. Bean实例化三种方式

在这里插入图片描述

3.1无参(重点掌握无参就行):

使用无参构造方法实例化 它会根据默认无参构造方法来创建类对象,如果bean中没有默认无参构造函数,将会创建失败

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>

3.2 工厂静态方法实例化

工厂的静态方法返回Bean实例:
新建一个StaticFactoryBean类(可改名),再在applicationcontext.xml改为这样:
在这里插入图片描述

3.3工厂实例方法实例化

工厂的非静态方法返回Bean实例
新建一个DynamicFactoryBean类(可改名),再在applicationcontext.xml改为这样:
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值