Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 445
Avner Levy Avatar asked Mar 22 '12 10:03

Avner Levy


People also ask

What is difference between request and prototype scope in Spring?

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.

What is prototype scope in Spring?

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.

Can we Autowire prototype bean?

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.

What is the difference between singleton and prototype scope in Spring?

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.


1 Answers

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.

like image 193
Avner Levy Avatar answered Oct 03 '22 10:10

Avner Levy