首页 > 解决方案 > 具有范围原型的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 的任何优势。

标签: javaspring

解决方案


它们完全不同。

Spring Managed Beans:每当您使用 @Bean 创建 bean 或使用 @Inject/@Autowired 调用任何 bean 时,它们都在 Spring 上下文中,它们可以执行与 Spring 相关的功能,或者从应用程序上下文中获取它(尽管不推荐,因为它是反对控制反转)。

非 Spring Managed Beans:每当您使用 new 创建 bean 时,它们都会从 Spring 上下文中移出,并且不能再在 Spring Managed Context 中使用。

使用 new 创建的对象不知道任何 Spring 注释和相关功能。


推荐阅读