spring的默认模式&hashmap成员变量
- singleton代表单例
- 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修改的问题(貌似会造成死循环,生成一个循环链表,这个还未看)。