Since neither singleton
nor prototype
scopes seem to fit you (you don't want a single object, but you don't want a new instance each time), you need another scope.
In a web-application context there is a ready solution - use request
scope - thus in every request/response cycle you will have only one instance of your bean, no matter where and how many times you inject it.
In a non-web application context you can define your own implementation of org.springframework.beans.factory.config.Scope
Update: after you clarified, this seems like a very strange case. What comes to my mind is the following:
- define two
FactoryBean
s (actually - subclasses of AbstractFactoryBean
)- one returning new object every time, and one returning the same object (both of them should be in singleton
scope)
- inject the
Foo
s with @Resource(name="prototypeFactoryBean")
and @Resource(name="singletonFactoryBean")
(instead of @Autowired
)
- the
singletonFactoryBean
can be designed to just return a singleton (injected in the factory bean class)
- the
prototypeFactoryBean
can create a new instance, cast the BeanFactory
(available through getBeanFactory()
) to AutowireCapableBeanFactory
and call .autowire(newlyCreatedBean)
, and then return it. (alternatively you can inject an ApplicationContext
and get its AutowireCapableBeanFactory
)
But this is overly complex and you will need extended spring knowledge even after my explanation :)
Furthermore I think you should reconsider your design instead of making the above 'quirks'
Update 2: After your comment, the naming concept is transferred to annotations - as I indicated above you can use @Resource(name="someBean")