Since neither singleton nor prototype tags seem to suit you (you don't need one object, but you don't want every new instance every time), you need a different scope.
In the context of the web application, there is a ready-made solution - use the request area - so in each request / response cycle you will have only one instance of your bean, regardless of where and how many times you enter it.
In the context of a non-web application, you can define your own implementation of org.springframework.beans.factory.config.Scope
Update: after you find out, this seems like a very strange case. The following occurs to me:
- define two
FactoryBean (in fact - subclasses of AbstractFactoryBean ) - each returning a new object each time and one returning the same object (both of them should be in singleton ) - type
Foo with @Resource(name="prototypeFactoryBean") and @Resource(name="singletonFactoryBean") (instead of @Autowired ) singletonFactoryBean can be designed to simply return a singleton (introduced in the factory bean class)prototypeFactoryBean can create a new instance, drop the BeanFactory (accessible via getBeanFactory() ) to AutowireCapableBeanFactory and call .autowire(newlyCreatedBean) and then return it. (alternatively you can enter ApplicationContext and get it AutowireCapableBeanFactory )
But this is too complicated, and you will need advanced knowledge of spring even after my explanation :)
Also, I think you should rethink your design instead of doing the above quirks.
Update 2: After your comment, the concept of naming is transferred to the annotations - as indicated above, you can use @Resource(name="someBean")
Bozho source share