Spring autowire and prototype scope
The following link provide alternative solutions for such scenarios: http://whyjava.wordpress.com/2010/10/30/spring-scoped-proxy-beans-an-alternative-to-method-injection/
The link talks about adding to Foo:
@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
class Foo
Which will cause a new instance for every call.
Avner Levy
Technology Leader at Check Point Software Technologies
Updated on August 08, 2021Comments
-
Avner Levy almost 3 years
I have a class named Bar with the following annotation:
@Configurable(autowire = Autowire.BY_TYPE)
On a private member I have the following annotation:
@Autowired(required = true) private Foo foo;
In the spring configuration I have a bean of class Foo. If the bean is defined with
scope="prototype"
it doesn't work and I get the following exception:NoSuchBeanDefinitionException: No matching bean of type Foo found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency
Once I change the injected bean scope to
"singleton"
it works fine.Isn't auto wiring of prototype scoped bean allowed?
Is there any workaround (beside getting the bean manually)?
Thanks in advance, Avner
-
Aaron Digulla over 9 years
-
-
Avner Levy over 12 yearsI'm aware of the differences between prototype and singleton, I just don't understand why should the bean scope have influence on the auto-wiring. I'm using spring 3.
-
Avner Levy almost 12 yearsThanks for your answer but removing the scope attribute won't fix my code since all Bar instances will share the same Foo instance which isn't what I need. In additional the Foo instance should be instantiated once per Bar object creation / injection and not per field usage (as far as my understanding).
-
vine almost 12 yearsi dont know if there is an alternative for your specific design, tell me if there is. But as far as design is concerned, beans should be used in a stateless way, it means be careful in your fields, make sure fields use in those beans are not global fields but method fields, in this way even its is singleton, you won't worry if it is shared by many classes since no global variable is shared,because it is Stateless.
-
tomekK about 8 yearsIt's nice what've you wrote, but it would be better if you would just write that configure it with proxy is required :)
-
Krzysztof Krasoń about 8 yearsOnly link answers are bad, what will happens if given links disappear?
-
Jack Straw almost 3 years@avner-levy The second link no longer works.
-
Avner Levy almost 3 yearsRemoved the broken link. Thanks for reporting @Jack Straw