简体   繁体   English

春季原型豆迷

[英]Spring prototype bean confiusion

Consider the following classes: 考虑以下类别:

@Component
@Scope(scopeName = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
class PrototypeBean
{
    public void method1() { ... };
    public void method2() { ... };
}

@Component
public class SingletonBean
{
   @Autowired
   private PrototypeBean prototypeBean;

   public void SingletonBean doSomething()
   {
      prototypeBean.method1();
      prototypeBean.method2();

   }
}

Now, I would expect that everytime doSomething() method is called, a new PrototypeBean instance is created and injected to SingletonBean. 现在,我希望每次调用doSomething()方法时,都会创建一个新的PrototypeBean实例并将其注入到SingletonBean中。 But what really happens is a new PrototypeBean instance is created and injected into SingletonBean when I call method1() and method2(). 但是真正发生的是,当我调用method1()和method2()时,创建了一个新的PrototypeBean实例并将其注入到SingletonBean中。

I don't really get why, this should've worked as far is I'm concerned. 我真的不明白为什么,就我而言,这应该行得通。 Please correct my if I'm wrong. 如果我错了,请更正我。

是的,这是可以预料的,因为仅按需初始化bean,对于原型范围,每次需要时都会初始化bean。

Yes, That is expected !! 是的,那是预期的!

Because you declared the bean's scope attribute as prototype @Scope(scopeName = "prototype") that force the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. 因为您将bean的scope属性声明为prototype @Scope(scopeName = "prototype") ,因此每次提出对该特定bean的请求时,Spring IoC容器都会强制创建该对象的新bean实例。

Note:As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans. 注意:通常,将原型作用域用于所有状态已满的bean,将单例作用域用于无状态bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM