NOTE

2.29 Bean作用域

1. 作用域分类 - singleton:每次从容器中获取的bean是同一个 - prototype:每次从容器中获取的bean,都会创建一个新的 - request:在Http请求中使用的同一个bean - session:在http session中使用的是同一个bean 2. 为什么有prot

Java创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 作用域分类

  • singleton:每次从容器中获取的bean是同一个
  • prototype:每次从容器中获取的bean,都会创建一个新的
  • request:在Http请求中使用的同一个bean
  • session:在http session中使用的是同一个bean

2. 为什么有prototype

  • 单例模式修改属性会有线程安全问题 比如
@Autowired
HttpServletRequest request;

这里注入的HttpServletRequest不会有线程安全问题就是他是prototype的

2.1. 怎么使用prototype

  • MainController
@RestController
public class MainController
{
	@Autowired
	MainServices services;
}
  • MainServices
@Service
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)//这里必须有ScopedProxyMode.TARGET_CLASS
public class MainServices
{
//...
}

3. 参考