Marty Chang
Marty Chang

Reputation: 6599

Spring prototype beans with parameters?

Is it possible to define a prototype bean, using XML config or annotation-based config such that I can get an instance of the bean with a custom parameter value? My use case is a message queue handler that makes API calls with different parameter values that are supplied in the inbound message.

In this case it seems I can do one of two things:

Perhaps a different way of wording my question is: What is the benefit of using a prototype-scope bean vs. using a simple Java constructor?

Upvotes: 3

Views: 2817

Answers (1)

Piotr Findeisen
Piotr Findeisen

Reputation: 20720

To get a prototype bean from another bean while passing arguments to constructor you can use <lookup-method> (XML Configuration) or @Lookup (annotation-based configuration).

If you want to get the prototype instance from "unmanaged" code (not from a bean) or you don't want to use the lookup methods, you can achieve the same using org.springframework.beans.factory.BeanFactory.getBean(String beanName, Object...).

Answering your second question, difference between a prototype-scope bean and using a simple Java constructor is that the prototype-scope bean still have access to Spring container's features. This includes, but it's not limited to the following: it can have collaborators provided in XML configuration (<property name="someCollaborator" ref="..."/>) or with annotations (@Resource, @Autowired, ...), t can implement Spring-aware interfaces (like ApplicationContextAware so that the prototype bean itself has access to the container).

Upvotes: 2

Related Questions