java - 具有范围原型的bean和单例bean中的新对象有什么区别?
问题描述
就像主题一样。我没有看到这些方法之间有任何区别。当我只使用这些时,原型 bean 很清楚。但是在春天,我们基于单例的 bean,所以当我在单例 bean 中使用具有范围原型的 bean 时,它看起来就像我想创建新对象一样。
@Service
public class SomeService{
@Autowired
private ApplicationContext applicationContext;
public void someClass() {
PrototypeObject prototypeObject = applicationContext.getBean(PrototypeObject .class);
PrototypeObject prototypeObject = new PrototypeObject();
}
}
这两种方法有区别吗?
对我来说最好的答案是:我失去了 IoC 的任何优势。
解决方案
它们完全不同。
Spring Managed Beans:每当您使用 @Bean 创建 bean 或使用 @Inject/@Autowired 调用任何 bean 时,它们都在 Spring 上下文中,它们可以执行与 Spring 相关的功能,或者从应用程序上下文中获取它(尽管不推荐,因为它是反对控制反转)。
非 Spring Managed Beans:每当您使用 new 创建 bean 时,它们都会从 Spring 上下文中移出,并且不能再在 Spring Managed Context 中使用。
使用 new 创建的对象不知道任何 Spring 注释和相关功能。
推荐阅读
- sql-server - 如何将我的本地 SQL Server 连接到 google colab?
- c# - 为什么每次都将我的作用域服务作为新实例调用?
- c# - 如何在实体框架中保存对象,同时为其列之一使用数据库生成的选项?
- gitlab - Sonarqube Gitlab 与 sonar-scanner.properties 文件的集成问题
- azure - Azure 表存储(表服务 REST API)SharedKeyLite 不工作
- javascript - 为什么我的 JSON 响应返回未定义?
- java - 我遇到错误,找不到解决方法
- matplotlib - matplotlit colorbar 标题挂在图外
- javascript - 如何在使用 twitter api 时修复 Brain.js 错误
- swift - 如何以编程方式将图像的大小调整为 NSImageView?