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:
- Get an instance of my prototype-scope bean and then call setters to customize it to be specific to the inbound message.
- Construct a new instance of the bean class using a plain
new MyPrototypeBean()
and then call setters to customize the instance.
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?
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 (likeApplicationContextAware
so that the prototype bean itself has access to the container).