将原型bean自动装入原型bean? [英] Autowire of prototype bean into prototype bean?

查看:138
本文介绍了将原型bean自动装入原型bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些现有的代码,它正在做我以前没见过的事情。我已经使用方法注入或使用getBean()从上下文中获取bean来处理将原型bean自动装配到单例中。我在我正在处理的代码中看到的是一个bean,它是一个原型并使用getBean()检索,并且它具有自动连接的依赖项。其中大部分是单身豆,这是有道理的。但是有一个另一个原型bean的autowire,从我看到的,它看起来好像是在获得一个新的bean。我的问题是当你将原型自动装配到原型中时,会给你一个新实例吗?由于autowire请求不是在启动时,而是在创建此bean时,是否会创建新实例?这违背了我对autowire和原型bean的看法,我希望能够从野外听到答案。感谢您的任何见解。我正在尝试最小化我对这段代码的重构,因为它有点意大利面。

I'm working with some existing code and it is doing things I haven't seen before. I've dealt with autowiring prototype beans into singletons using method injection or getting the bean from the context using getBean(). What I am seeing in this code I am working on is a bean that is a prototype and retrieved using getBean(), and it has autowired dependencies. Most of these are singleton beans, which makes sense. But there is an autowire of another prototype bean, and from what I see, it does seem like it is getting a new bean. My question is when you autowire a prototype into a prototype, will that give you a new instance? Since the autowire request is not at startup but rather when this bean is created, does it go and create a new instance? This goes against what I thought about autowire and prototype beans and I wanted to hear an answer from out in the wild. Thanks for any insight. I'm trying to minimize my refactoring of this code as it is a bit spaghetti-ish.

例如:

@Scope("prototype")
public class MyPrototypeClass  {

    @Autowired
    private ReallyGoodSingletonService svc;

    @Autowired
    private APrototypeBean bean;

    public void doSomething() {
        bean.doAThing();
    }
}

@Scope("prototype)
public class APrototypeBean {
   private int stuffgoeshere;

   public void doAThing() {
   }
}

所以当MyPrototypeClass中的doSomething()时被称为,bean是MyPrototypeClass的每个实例的单例还是新单元?

So when doSomething() in MyPrototypeClass is called, is that "bean" a singleton or a new one for each instance of MyPrototypeClass?

推荐答案

在您的示例中, APrototypeBean bean将被设置为一个全新的bean,它会一直存在,直到你创建的 MyPrototypeClass 的实例被销毁。

In your example, the APrototypeBean bean will be set to a brand new bean which will live through until the instance of MyPrototypeClass that you created is destroyed.

如果您创建 MyPrototypeClass 的第二个实例,那么第二个实例将收到自己的 APrototypeBean 。使用当前配置,每次调用 doSomething()时,将在 APrototypeBean 对于 MyPrototypeClass 对象是唯一的。

If you create a second instance of MyPrototypeClass then that second instance will receive its own APrototypeBean. With your current configuration, every time you call doSomething(), the method will be invoked on an instance of APrototypeBean that is unique for that MyPrototypeClass object.

这篇关于将原型bean自动装入原型bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆