spring默认单例

spring的默认模式&hashmap成员变量

  1. singleton代表单例
  2. prototype代表多例
package com.lyb.springBeanTest;

import com.lyb.merchantWithholding.util.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author lyb
 * @date 2023/3/30 15:50
 */
@Service
@Scope("prototype")
public class TestBeanProperties {
    private String aa = "123";
    public String test(String flag){
        String s = UUID.randomUUID().toString();
        if ("1".equals(flag)) {
            aa = s;
        }
        return aa;
    }
}
 @Autowired
    private TestBeanProperties testBeanProperties;
    @RequestMapping("/getBeanPro/{flag}")
    @ResponseBody
    public String getBeanPro(@PathVariable("flag") String flag) throws IOException {
        return testBeanProperties.test(flag);
    }

@Autowired :每次的调用结果,使用spring自动注入的模式

http://localhost:9002/getBeanPro/2:123
http://localhost:9002/getBeanPro/1:随机值
http://localhost:9002/getBeanPro/2:上次的随机值
http://localhost:9002/getBeanPro/2:上次的随机值

由此可见,spring默认是单例模式,哪怕声明了多例,但是使用自动注入的模式,此处还是使用的单例模式。


hashMap作为一个非线程安全的双列集合,为什么我们实际使用的时候都使用的是hashmap呢?

01、刚才上面验证spring默认单例的时候,修改成员变量的时候,每个线程访问都是成员变量的值,但是我们使用hashmap的时候大多都是把他作为局部变量来使用的,所以不存在线程安全的问题。

02、哪怕我们偶尔作为成员变量也只是初始化一些常量,在使用的过程中不会修改成员变量的值,所以实际开发过程中很少会遇到因为多线程导致的haspmap修改的问题(貌似会造成死循环,生成一个循环链表,这个还未看)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值