Avner Levy Avner Levy - 4 months ago 32
Java Question

Spring autowire and prototype scope

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
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
it works fine.

Isn't auto wiring of prototype scoped bean allowed?

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

Thanks in advance,


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:

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

Which will cause a new instance every call.