Spring autowire and prototype scope

前端 未结 3 625
醉酒成梦
醉酒成梦 2020-12-31 07:09

I have a class named Bar with the following annotation: @Configurable(autowire = Autowire.BY_TYPE)

On a private member I have the following annotation:

相关标签:
3条回答
  • 2020-12-31 07:26

    The following links provide alternative solutions for such scenarios:

    1. http://whyjava.wordpress.com/2010/10/30/spring-scoped-proxy-beans-an-alternative-to-method-injection/
    2. http://benkiew.wordpress.com/2012/04/22/spring-2-5-x-create-prototype-instances-from-code/

    The first link talks about adding to Foo:

    @Component
    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
    class Foo
    

    Which will cause a new instance every call.

    0 讨论(0)
  • 2020-12-31 07:26

    I believe its the prototype/singleton thing declared in your xml for that bean is the issue.

    Isn't auto wiring of prototype scoped bean allowed?

    I think it is not allowed. The logic is if it is allowed, then whenever you use that class, then it needs to reinstantiate that bean always as its field. Which is weird especially if the class that this bean is autowired as a field is a singleton itself.

    is there any workaround (beside getting the bean manually)?

    Just try to remove the scope attribute, cause if it is of prototype attribute, it won't be retrieved. If those beans(services and DAO) are declared in your applicationContext, just let the autowire annotation get it as singleton since by default beans are singleton, which it should be.

    0 讨论(0)
  • 2020-12-31 07:49

    If the injected bean scope is 'Singleton', the same instance of the bean will be auto-wired. If the injected bean scope is 'prototype', new instance will be created as part of auto-wire process.

    What version of Spring you are using and also attach the spring-context.xml for more details.

    0 讨论(0)
提交回复
热议问题