Spring单例、多例、懒加载

1.说明

单例:内存中只有一份
多例:内存中有多份
  • 默认情况下,spring管理的都是单例模式
package com.jt.config;

import com.jt.demo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
@ComponentScan("com.jt")
public class SpringConfig {
    @Bean
//    @Scope("singleton") //默认值 单例模式
    @Scope("prototype") //多例模式

    public User user(){
        return new User();
    }
}

2.懒加载
  1. 如果spring容器创建,对象立即创建则该方式称为“立即启动” – 容器启动创建
  2. 如果spring容器创建,对象在被使用时才创建,被称为“懒加载” --用时创建

@Lazy 表示懒加载
测试

package com.jt.config;

import com.jt.demo.User;
import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("com.jt")
public class SpringConfig {
    @Bean
//    @Scope("singleton") //默认值 单例模式
    //@Scope("prototype") //多例模式
    @Lazy
    public User user(){
        return new User();
    }
}

打个断点,查看什么时候创建加载
请添加图片描述
请添加图片描述
请添加图片描述

多例和懒加载的关系

  • 只要是多例模式都是懒加载,只有在单例模式下才能控制懒加载有效
什么时候才能用到懒加载

1.服务器启动时,如果加载太多资源必然导致服务器启动慢,适当的将不重要的资源设置为懒加载。
2.有时用户会需要一些特殊的“链接”,而这些链接的创建需要时间很长,可以使用懒加载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值