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
prototype – A new instance will be created every time the bean is requested from the spring container. request – This is same as prototype scope, however it's meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
Prototype Scope:If the scope is declared prototype, then spring IOC container will create a new instance of that bean every time a request is made for that specific bean. A request can be made to the bean instance either programmatically using getBean() method or by XML for Dependency Injection of secondary type.
When you autowire a prototype bean, Spring will initialize a new instance of the bean. If you autowire the bean in multiple places, then Spring will create a new instance for every place you autowire the bean. Let us demonstrate this behavior by creating a test bean and a spring test where we autowire our test beans.
Prototype scope: A new object is created each time it is injected. Singleton scope: The same object is returned each time it is injected. Prototype scope is used for all beans that are stateful, while the singleton scope should be used for stateless beans.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With